Elasticsearch 查询:获取前缀与查询匹配的所有结果,以实现预输入、自动完成功能

Elasticsearch query: Fetch all the results which prefix matches the query for typeahead, autocomplete feature

query
what is my name
what is google
what is Whosebug
how to search

所以,我想要一个包含上述文档的 Elasticsearch 索引。我想获取前缀与查询匹配的所有结果。例如,当查询“what is”时,我需要 {"what is my name", "what is google", "what is Whosebug"} 作为结果,精确前缀匹配。

如何创建索引?和示例查询(如果可能)。

提前致谢。

multiple ways to achieve what you want, but simplest is to use the prefix query,如果你直接将数据索引到Elasticsearch而不定义映射,它会自动为你创建两个字段,在.keyword字段上你可以使用前缀查询作为如下所示。

索引示例文档

PUT <your-es-index>/_doc/1

{
    "title" : "what is my name"
}

PUT <your-es-index>/_doc/2

{
    "title" : "what is google"
}

PUT <your-es-index>/_doc/3

{
    "title" : "what is Whosebug"
}

PUT <your-es-index>/_doc/4

{
    "title" : "how to search"
}

搜索查询

POST /_search

{
    "query": {
        "prefix": {
            "title.keyword": {
                "value": "what is"
            }
        }
    }
}

您预期的搜索结果

"hits": [
            {
                "_index": "72391510",
                "_id": "1",
                "_score": 1.0,
                "_source": {
                    "title": "what is my name"
                }
            },
            {
                "_index": "72391510",
                "_id": "2",
                "_score": 1.0,
                "_source": {
                    "title": "what is google"
                }
            },
            {
                "_index": "72391510",
                "_id": "3",
                "_score": 1.0,
                "_source": {
                    "title": "what is Whosebug"
                }
            }