首页 > 解决方案 > Elasticsearch 一个数组至少包含一个元素

问题描述

我正在尝试使用弹性搜索按标签搜索食谱

{
  ...
  "tag": [
      "cool",
      "cooler"
  ]
},
{
  ...
  "tag": [
      "cool",
      "hard"
  ]
},
{
  ...
  "tag": [
      "coolest",
      "hardest"
  ]
},

我想搜索所有包含“酷”标签的实体

我尝试了什么:

GET /recipes/_search
{
  "query": {
    "terms": {
      "tag": ["cool"]
    }
  }
}

什么都不退

GET /recipes/_search
{
  "query": {
    "bool": {
      "should": [
        {
          "term": {
            "tag": "cool"
          }
        }
      ]
    }
  }
}

什么都不退

GET /recipes/_search
{
  "query": {
    "bool": {
      "should": [
        {
          "match": {
            "tag": "cool"
          }
        }
      ]
    }
  }
}

返回所有实体

如何仅检索包含“酷”和可能其他值但规则是标签必须存在于标签数组中的项目

标签: elasticsearch

解决方案


本解决方案使用脚本查询脚本查询

GET /recipes/_search
{
  "query": {
    "bool": {
      "must": {
        "script": {
          "script": {
            "source": "doc['tag'] instanceof List && doc['tag'][0].contains('cool')"
          }
        }
      }
    }
  }
}

推荐阅读