你所需要的是
multi-match query,但它的表现并不完全符合你的期望。
比较
multi_match
和
query_string
在
validate输出的结果。
使用运算符
and
的
multi_match
将确保所有术语都存在于至少一个字段中:
curl -XGET 'http://127.0.0.1:9200/_validate/query?pretty=1&explain=true' -d '
{
"multi_match" : {
"operator" : "and",
"fields" : [
"firstname",
"lastname"
],
"query" : "john smith"
}
}
'
使用默认运算符 AND
的 query_string
将检查每个词项是否存在于至少一个字段中:
curl -XGET 'http://127.0.0.1:9200/_validate/query?pretty=1&explain=true' -d '
{
"query_string" : {
"fields" : [
"firstname",
"lastname"
],
"query" : "john smith",
"default_operator" : "AND"
}
}
'
所以您有几个选择来实现您想要的目标:
在使用query_string
之前,预处理搜索词,以删除通配符等内容
预处理搜索词以提取每个单词,然后为每个单词生成一个multi_match
查询
在映射中使用index_name
来为名称字段索引它们的数据到单个字段中,您可以将其用于搜索(类似于自己的自定义all
字段):
如下所示:
curl -XPUT 'http://127.0.0.1:9200/test/?pretty=1' -d '
{
"mappings" : {
"test" : {
"properties" : {
"firstname" : {
"index_name" : "name",
"type" : "string"
},
"lastname" : {
"index_name" : "name",
"type" : "string"
}
}
}
}
}
'
curl -XPOST 'http://127.0.0.1:9200/test/test?pretty=1' -d '
{
"firstname" : "john",
"lastname" : "smith"
}
'
curl -XGET 'http://127.0.0.1:9200/test/test/_search?pretty=1' -d '
{
"query" : {
"match" : {
"name" : {
"operator" : "and",
"query" : "john smith"
}
}
}
}
'
请注意,
firstname
和
lastname
不再可以独立搜索。这两个字段的数据已经被索引到
name
中。
您可以使用
multi-fields和
path
参数使它们既可以独立搜索,也可以一起搜索,如下所示:
curl -XPUT 'http:
{
"mappings" : {
"test" : {
"properties" : {
"firstname" : {
"fields" : {
"firstname" : {
"type" : "string"
},
"any_name" : {
"type" : "string"
}
},
"path" : "just_name",
"type" : "multi_field"
},
"lastname" : {
"fields" : {
"any_name" : {
"type" : "string"
},
"lastname" : {
"type" : "string"
}
},
"path" : "just_name",
"type" : "multi_field"
}
}
}
}
}
'
curl -XPOST 'http:
{
"firstname" : "john",
"lastname" : "smith"
}
'
搜索 任意名称
字段可行:
curl -XGET 'http://127.0.0.1:9200/test/test/_search?pretty=1' -d '
{
"query" : {
"match" : {
"any_name" : {
"operator" : "and",
"query" : "john smith"
}
}
}
}
'
搜索 firstname
中的 john AND smith
不起作用:
curl -XGET 'http://127.0.0.1:9200/test/test/_search?pretty=1' -d '
{
"query" : {
"match" : {
"firstname" : {
"operator" : "and",
"query" : "john smith"
}
}
}
}
'
但是仅搜索名字为john
的firstname
可以正常工作:
curl -XGET 'http://127.0.0.1:9200/test/test/_search?pretty=1' -d '
{
"query" : {
"match" : {
"firstname" : {
"operator" : "and",
"query" : "john"
}
}
}
}
'