我有一个 3 级嵌套对象,如下所示,我想在弹性搜索中索引这些对象。这里的要求是用户将编写一个搜索查询关键字,例如"关键字 1 关键字 2 ..."我想返回包含所有这些关键字的对象(在任何级别,即 AND 操作(。
[
{
"country":[
{
"name":"India",
"ext_code":"91",
"states":[
{
"name":"Karnataka",
"ext_code":"04",
"cities":[
{
"name":"Bangalore",
"ext_code":"080"
}
]
}
]
}
]
}
]
目前,我使用以下映射以嵌套格式存储它们:
{
"mappings":{
"doc":{
"properties":{
"name": {"type":"text"},
"ext_code": {"type":"text"}
"state" {
"type": "nested",
"properties": {
"name": {"type":"text"},
"ext_code": {"type":"text"}
"city" {
"type": "nested",
"properties": {
"name": {"type":"text"}
"ext_code": {"type":"text"}
}
}
}
}
}
}
}
}
在搜索时,我向弹性搜索传递嵌套查询以在所有级别上进行搜索,如下所示:
{
"query": {
"bool": {
"should": [
{
"multi_match": {
"query": "keyword1 keyword2 ...",
"fields": ['name']
}
},
{
"nested": {
"path": 'state',
"query": {
"multi_match": {
"query": "keyword1 keyword2 ...",
"fields": ['state.name']
}
}
}
},
{
"nested": {
"path": 'state.city',
"query": {
"multi_match": {
"query": "keyword1 keyword2 ...",
"fields": ['state.city.name']
}
}
}
}
]
}
}
}
发送多个令牌进行搜索时,它会应用 OR 操作,返回包含任何搜索令牌的文档。
有没有办法将弹性搜索配置为对搜索查询中的多个令牌执行 AND 操作?
一种解决方案是索引自定义all
字段中name
字段的所有值。首先定义索引和映射,如下所示:
PUT index
{
"mappings": {
"doc": {
"properties": {
"all": { <-- all field that will contain all values
"type": "text"
},
"name": {
"type": "text",
"copy_to": "all" <-- copy value to all field
},
"ext_code": {
"type": "text"
},
"state": {
"type": "nested",
"properties": {
"name": {
"type": "text",
"copy_to": "all" <-- copy value to all field
},
"ext_code": {
"type": "text"
},
"city": {
"type": "nested",
"properties": {
"name": {
"type": "text",
"copy_to": "all" <-- copy value to all field
},
"ext_code": {
"type": "text"
}
}
}
}
}
}
}
}
}
然后为您的文档编制索引:
POST index/doc
{
"name": "India",
"ext_code": "91",
"state": [
{
"name": "Karnataka",
"ext_code": "04",
"city": [
{
"name": "Bangalore",
"ext_code": "080"
}
]
}
]
}
最后,使用简单的匹配查询,您可以在文档中的任意位置搜索任何值:
POST index/_search
{
"query": {
"bool": {
"must": [
{
"match": {
"all": {
"query": "bangalore india",
"operator": "and"
}
}
}
]
}
}
}
请尝试以下操作
{
"query": {
"bool": {
"should": [
{
"simple_query_string": {
"query": "keyword1 keyword2 ...",
"fields": ['name'] ,
"default_operator": "and"
}
},
{
"nested": {
"path": 'state',
"query": {
"simple_query_string": {
"query": "keyword1 keyword2 ...",
"fields": ['state.name'],
"default_operator": "and"
}
}
}
},
{
"nested": {
"path": 'state.city',
"query": {
"simple_query_string": {
"query": "keyword1 keyword2 ...",
"fields": ['state.city.name'],
"default_operator": "and"
}
}
}
}
]
}
}
}
我认为multi_match不适合这个要求。简单查询字符串或查询字符串查询更适合此目的。
- https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-query-string-query.html
- https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-query-string-query.html