ElasticSearch:查询嵌套数组

3pvhb19x  于 2023-02-18  发布在  ElasticSearch
关注(0)|答案(1)|浏览(152)

我正在尝试编写多字段查询的搜索功能,但是在嵌套数组中进行全文搜索时存在一些问题
我的数据格式如下:

{
  "name": "[Sample] AAA",
  "variant": [
    ["s", "black"],
    ["l", "white"],
  ],
},
{
  "name": "[Sample] BBB",
  "variant": [
    ["s", "white"],
    ["l", "black"],
  ],
},

对于输入sample s blacksample black s,我希望找到所有具有sblack选项(如[Sample] AAA,但不包括[Sample] BBB)的文档。我尝试了nested查询,但没有得到所需的结果。是否有任何方法可以重构数据格式并编写最佳Map?

xqkwcwgp

xqkwcwgp1#

使用以下Map创建索引

PUT my_index
{
  "mappings": {
    "properties": {
      "name": {
        "type": "text"
      },
      "variant": {
        "type": "nested",
        "properties": {
          "0": {
            "type": "keyword"
          },
          "1": {
            "type": "text"
          }
        }
      }
    }
  }
}
  • 把样本文件
PUT my_index/_doc/1
{
  "name": "[Sample] AAA",
  "variant": [
    ["s", "black"],
    ["l", "white"],
  ]
}

PUT my_index/_doc/2
{
  "name": "[Sample] BBB",
  "variant": [
    ["s", "white"],
    ["l", "black"],
  ]
}
  • 去拿文件
GET my_index/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "nested": {
            "path": "variant",
            "query": {
              "bool": {
                "must": [
                  {
                    "match": {
                      "variant.key": "s"
                    }
                  },
                  {
                    "match": {
                      "variant.value": "black"
                    }
                  }
                ]
              }
            }
          }
        }
      ]
    }
  }
}

相关问题