【发布时间】:2021-02-27 00:35:38
【问题描述】:
我正在尝试将“键入时搜索”功能添加到 Elasticsearch 中名为 email_address 的字段中。我对from the docs 的理解是,如果我创建一个search_as_you_type 字段,它应该会自动创建为查找部分匹配而优化的ngram 子字段。
但是,它似乎没有按我预期的方式工作,而且我似乎没有从这种特殊字段类型中获得预期的好处。
首先,我创建了一个索引:
$ curl -s -H 'Content-Type: application/json' -XPUT http://localhost:9200/mytestindex -d '
{
"mappings": {
"properties": {
"email_address": {"type": "search_as_you_type"}
}
}
}
'
当我请求新创建的电子邮件字段时,我看到的是:
$ curl -s -H 'Content-Type: application/json' http://localhost:9200/mytestindex/_mapping/field/email_address | json_pp
{
"mytestindex" : {
"mappings" : {
"email_address" : {
"full_name" : "email_address",
"mapping" : {
"email_address" : {
"max_shingle_size" : 3,
"type" : "search_as_you_type"
}
}
}
}
}
}
最后,我填充了一些示例数据:
$ curl -s -H 'Content-Type: application/json' http://localhost:9200/mytestindex/_doc -d '
{"email_address": "sam@example.com"}'
$ curl -s -H 'Content-Type: application/json' http://localhost:9200/mytestindex/_doc -d '
{"email_address": "sally@example.com"}'
$ curl -s -H 'Content-Type: application/json' http://localhost:9200/mytestindex/_doc -d '
{"email_address": "jane@example.com"}'
$ curl -s -H 'Content-Type: application/json' http://localhost:9200/mytestindex/_doc -d '
{"email_address": "samantha@example.com"}'
官方文档建议使用 bool_prefix multi_match 搜索以下字段:email_address、email_address._2gram 和 email_address._3gram。好奇地尝试子字段,我测试了只包含它们的搜索,但我无法得到任何结果:
$ curl -s -H 'Content-Type: application/json' http://localhost:9200/mytestindex/_search -d '
{
"query": {
"multi_match": {
"query": "sa",
"type": "bool_prefix",
"fields": [
"email_address._2gram",
"email_address._3gram"
]
}
}
}
' | json_pp
{
"hits" : {
"hits" : [],
"max_score" : null,
"total" : {
"value" : 0,
"relation" : "eq"
}
},
"took" : 4,
"_shards" : {
"skipped" : 0,
"successful" : 1,
"total" : 1,
"failed" : 0
},
"timed_out" : false
}
我尝试了各种长度的部分查询(s、sa、sam 等),但从未得到任何结果。
当我执行相同的搜索但只包含 email_address 字段本身时,我会得到我期望的所有结果:
curl -s -H 'Content-Type: application/json' http://localhost:9200/mytestindex/_search -d '
{
"query": {
"multi_match": {
"query": "sa",
"type": "bool_prefix",
"fields": [
"email_address"
]
}
}
}
' | json_pp
{
"timed_out" : false,
"hits" : {
"max_score" : 1,
"total" : {
"relation" : "eq",
"value" : 3
},
"hits" : [
{
"_index" : "mytestindex",
"_id" : "gEbkCXUBC6_J-EeLAygM",
"_score" : 1,
"_type" : "_doc",
"_source" : {
"email_address" : "sam@example.com"
}
},
{
"_index" : "mytestindex",
"_source" : {
"email_address" : "sally@example.com"
},
"_score" : 1,
"_type" : "_doc",
"_id" : "gUbkCXUBC6_J-EeLWigu"
},
{
"_index" : "mytestindex",
"_id" : "jUb5CXUBC6_J-EeL1ij1",
"_type" : "_doc",
"_score" : 1,
"_source" : {
"email_address" : "samantha@example.com"
}
}
]
},
"took" : 2,
"_shards" : {
"failed" : 0,
"skipped" : 0,
"successful" : 1,
"total" : 1
}
}
因此,我不明白_2gram 和_3gram 子字段有什么好处。我是否设置错误?还是我对这些字段的实际用途感到困惑?
【问题讨论】:
-
您有机会浏览我的回答吗,期待您的反馈????
标签: elasticsearch