实际上,我不久前为Qbox 写了一篇关于此的博客文章,您可以在此处找到:http://blog.qbox.io/multi-field-partial-word-autocomplete-in-elasticsearch-using-ngrams。 (不幸的是,帖子中的某些链接已损坏,目前无法轻松修复,但希望您能明白这一点。)
我将向您推荐该帖子以了解详细信息,但这里有一些代码可用于快速测试它。请注意,我使用的是edge ngrams,而不是完整的ngrams。
还要特别注意_all field和match query operator的使用。
好的,下面是映射:
PUT /test_index
{
"settings": {
"analysis": {
"filter": {
"edgeNGram_filter": {
"type": "edgeNGram",
"min_gram": 2,
"max_gram": 20
}
},
"analyzer": {
"edgeNGram_analyzer": {
"type": "custom",
"tokenizer": "whitespace",
"filter": [
"lowercase",
"asciifolding",
"edgeNGram_filter"
]
}
}
}
},
"mappings": {
"doc": {
"_all": {
"enabled": true,
"index_analyzer": "edgeNGram_analyzer",
"search_analyzer": "standard"
},
"properties": {
"field1": {
"type": "string",
"include_in_all": true
},
"field2": {
"type": "string",
"include_in_all": true
}
}
}
}
}
现在添加一些文档:
POST /test_index/doc/_bulk
{"index":{"_id":1}}
{"field1":"purple duck","field2":"brown fox"}
{"index":{"_id":2}}
{"field1":"slow purple duck","field2":"quick brown fox"}
{"index":{"_id":3}}
{"field1":"red turtle","field2":"quick rabbit"}
这个查询似乎说明了你想要什么:
POST /test_index/_search
{
"query": {
"match": {
"_all": {
"query": "purp fo slo",
"operator": "and"
}
}
}
}
返回:
{
"took": 5,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"failed": 0
},
"hits": {
"total": 1,
"max_score": 0.19930676,
"hits": [
{
"_index": "test_index",
"_type": "doc",
"_id": "2",
"_score": 0.19930676,
"_source": {
"field1": "slow purple duck",
"field2": "quick brown fox"
}
}
]
}
}
这是我用来测试它的代码:
http://sense.qbox.io/gist/b87e426062f453d946d643c7fa3d5480cd8e26ec