21

我在使用弹性搜索查询时遇到问题。我希望能够对结果进行排序,但 elasticsearch 忽略了排序标签。这是我的查询:

{
    "sort": [{
        "title": {"order": "desc"}
    }],
    "query":{
        "term": { "title": "pagos" }
    }
}

但是,当我删除查询部分并仅发送排序标签时,它可以工作。谁能指出我正确的方法?

我还尝试了以下查询,这是我拥有的完整查询:

{
  "sort": [{
    "title": {"order": "asc"}
  }],
  "query":{
    "bool":{
      "should":[
        {
          "match":{
            "title":{
              "query":"Pagos",
              "boost":9
            }
          }
        },
        {
          "match":{
            "description":{
              "query":"Pagos",
              "boost":5
            }
          }
        },
        {
          "match":{
            "keywords":{
              "query":"Pagos",
              "boost":3
            }
          }
        },
        {
          "match":{
            "owner":{
              "query":"Pagos",
              "boost":2
            }
          }
        }
      ]
    }
  }
}

设置

{
  "settings": {
    "analysis": {
      "filter": {
        "autocomplete_filter": {
          "type": "ngram",
          "min_gram": 3,
          "max_gram": 15,
          "token_chars": [
            "letter",
            "digit",
            "punctuation",
            "symbol"
          ]
        }
      },
      "analyzer": {
        "default" : {
          "tokenizer" : "standard",
          "filter" : ["standard", "lowercase", "asciifolding"]
        },
        "autocomplete": {
          "type": "custom",
          "tokenizer": "standard",
          "filter": [
            "lowercase",
            "asciifolding",
            "autocomplete_filter"
          ]
        }
      }
    }
  }
}

映射

{
  "objects": {
    "properties": {
      "id":             { "type": "string", "index": "not_analyzed" },
      "type":           { "type": "string" },
      "title":          { "type": "string", "boost": 9, "analyzer": "autocomplete", "search_analyzer": "standard" },
      "owner":          { "type": "string", "boost": 2 },
      "description":    { "type": "string", "boost": 4 },
      "keywords":       { "type": "string", "boost": 1 }
    }
  }
}

提前致谢!

4

1 回答 1

25

你的文档中的“title”字段是一个解析过的字符串字段,也是一个多值字段,也就是说elasticsearch会将字段的内容拆分成token,分别存储在索引中。您可能希望在第一个术语上按字母顺序对“标题”字段进行排序,然后在第二个术语上进行排序,依此类推,但 elasticsearch 在排序时没有此信息可供使用。

因此,您可以从以下位置更改“标题”字段的映射:

{
  "title": {
    "type": "string", "boost": 9, "analyzer": "autocomplete", "search_analyzer": "standard"
  }
}

进入这样的多字段映射:

{
  "title": {
    "type": "string", "boost": 9, "analyzer": "autocomplete", "search_analyzer":"standard",
    "fields": {
      "raw": {
        "type": "string",
        "index": "not_analyzed"
      }
    }
  }
}

现在根据已分析 的“title”字段执行搜索并根据not_analyzed “title.raw”字段进行排序

{
    "sort": [{
        "title.raw": {"order": "desc"}
    }],
    "query":{
        "term": { "title": "pagos" }
    }
}

这里解释得很漂亮:字符串排序和多字段

于 2015-12-28T14:37:33.287 回答