Elasticsearch-如何在顶部列出完全匹配

时间:2018-10-05 14:17:30

标签: elasticsearch search full-text-search

我正在Elasticsearch中搜索“ Adana”一词,并希望将其排在最前面,因为它是确切的词,但事实并非如此。

“ Bilmemne Adana Otel”位于顶部。

普通查询没有任何好处,因此我尝试使用“必须”和“应该”进行布尔查询。但这也没有改变。

除此之外,如果我写“ Ada”,那么“ Adana”也应该排在第一位。

我们如何使其正常工作?

查询:

curl -X GET "localhost:9200/destinations/_search" -H 'Content-Type: 
application/json' -d'
{
 "query": {
   "match": {
     “Name”: {
       "query": “Adana”
      }
    }
  }
}
'

结果:

{
"took" : 16,
"timed_out" : false,
"_shards" : {
    "total" : 5,
    "successful" : 5,
    "skipped" : 0,
    "failed" : 0
},
"hits" : {
    "total" : 3,
    "max_score" : 3.255435,
    "hits" : [
    {
        "_index" : "destinations",
        "_type" : "_doc",
        "_id" : "10",
        "_score" : 3.255435,
        "_source" : {
        "name" : "Bilmemne Adana Otel"
        }
    },
    {
        "_index" : "destinations",
        "_type" : "_doc",
        "_id" : "4",
        "_score" : 2.8624198,
        "_source" : {
        "name" : "Adana"
        }
    },
    {
        "_index" : "destinations",
        "_type" : "_doc",
        "_id" : "1",
        "_score" : 2.3216834,
        "_source" : {
        "name" : "Adana Airport Otel - Adana"
        }
    }
    ]
}
}

索引:

{
"settings": {
    "analysis": {
    "filter": {
        "autocomplete_filter": {
        "type": "edge_ngram",
        "min_gram": 2,
        "max_gram": 15
        }
    },
    "analyzer": {
        "autocomplete": { 
        "type": "custom",
        "tokenizer": "standard",
        "filter": [
            "lowercase",
            "autocomplete_filter"
        ]
        }
    }
    }
},
"mappings": {
    "_doc": {
    "properties": {
        "name": {
        "type": "text",
        "analyzer": "autocomplete", 
        "search_analyzer": "standard" 
        }
    }
    }
}
}

1 个答案:

答案 0 :(得分:1)

如果您希望精确匹配位于最前面,则可以在映射中使用keyword字段。

{
  "settings": {
    "analysis": {
      "filter": {
        "autocomplete_filter": {
          "type": "edge_ngram",
          "min_gram": 3,
          "max_gram": 15
        }
      },
      "analyzer": {
        "autocomplete": {
          "type": "custom",
          "tokenizer": "standard",
          "filter": [
            "lowercase",
            "autocomplete_filter"
          ]
        }
      }
    }
  },
  "mappings": {
    "_doc": {
      "properties": {
        "name": {
          "type": "text",
          "fields": {
            "keyword": {
              "type": "keyword"
            }
          },
          "analyzer": "autocomplete",
          "search_analyzer": "standard"
        }
      }
    }
  }
}

然后,您可以进行一个bool查询,该查询在keyword查询中使用您的should

{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "name": "Adana"
          }
        }
      ],
      "should": [
        {
          "term": {
            "name.keyword": {
              "value": "Adana"
            }
          }
        }
      ]
    }
  }
}

那应该将完全匹配推到顶部。