Elasticsearch completion suggest search with multiple-word inputs

心不动则不痛 提交于 2019-12-03 07:01:13

The completion suggester is a prefix suggester, meaning it tries to match your query to the first few characters of the inputs that it's been given. If you want the document you posted to match the text "dog", then you'll need to specify "dog" as an input.

PUT /test_index/item/1
{
   "test_suggest": {
      "input": [
         "cat dog",
         "elephant",
         "dog"
      ]
   }
}

In my experience, the limitation of having to specify inputs to match makes completion suggesters less useful that other ways to implement prefix matching. I like edge ngrams for this purpose. I recently wrote a blog post about using ngrams that you might find helpful: http://blog.qbox.io/an-introduction-to-ngrams-in-elasticsearch

As a quick example, here is a mapping you could use

PUT /test_index
{
   "settings": {
      "analysis": {
         "filter": {
            "edge_ngram_filter": {
               "type": "edge_ngram",
               "min_gram": 2,
               "max_gram": 20
            }
         },
         "analyzer": {
            "edge_ngram_analyzer": {
               "type": "custom",
               "tokenizer": "standard",
               "filter": [
                  "lowercase",
                  "edge_ngram_filter"
               ]
            }
         }
      }
   },
   "mappings": {
      "item": {
         "properties": {
            "text_field": {
               "type": "string",
               "index_analyzer": "edge_ngram_analyzer",
               "search_analyzer": "standard"
            }
         }
      }
   }
}

then index the doc like this:

PUT /test_index/item/1
{
   "text_field": [
      "cat dog",
      "elephant"
   ]
}

and any of these queries will return it:

POST /test_index/_search
{
    "query": {
        "match": {
           "text_field": "dog"
        }
    }
}

POST /test_index/_search
{
    "query": {
        "match": {
           "text_field": "ele"
        }
    }
}

POST /test_index/_search
{
    "query": {
        "match": {
           "text_field": "ca"
        }
    }
}

Here's the code all together:

http://sense.qbox.io/gist/4a08fbb6e42c34ff8904badfaaeecc01139f96cf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!