我有一个3级嵌套对象,如下所示,我想在弹性搜索中为这些对象建立索引。这里的要求是用户将编写一个搜索查询关键字,例如“ keyword1 keyword2 ...”,并且我想返回包含所有这些关键字的对象(在任何级别,即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']
}
}
}
}
]
}
}
}
当发送多个令牌进行搜索时,它将应用“或”运算,返回包含任何搜索令牌的文档。
有没有一种方法可以配置Elastic Search对搜索查询中的多个令牌执行AND操作?
一种解决方案是name
在自定义all
字段中索引字段的所有值。首先定义您的索引和映射,如下所示:
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"
}
}
}
]
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句