gpt4 book ai didi

elasticsearch - 在 Elasticsearch 中存储嵌套对象

转载 作者:行者123 更新时间:2023-11-29 02:49:59 25 4
gpt4 key购买 nike

我有一个如下所示的 3 级嵌套对象,我想在 Elasticsearch 中索引这些对象。这里的要求是用户将编写一个搜索查询关键字,如“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"}
}
}
}
}
}
}
}
}

在搜索时,我将嵌套查询传递给 Elasticsearch 以在所有级别上进行搜索,如下所示:

{
"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 操作返回包含任何搜索标记的文档。

有没有办法配置 Elastic Search 来对搜索查询中的多个标记执行 AND 运算?

最佳答案

一个解决方案是索引自定义 all fieldname 字段的所有值.首先像这样定义你的索引和映射:

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"
}
}
}
]
}
}
}

关于elasticsearch - 在 Elasticsearch 中存储嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52530831/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com