如果字段有值,如何编写数组中包含值的elasticsearch查询

2fjabf4q  于 2021-06-15  发布在  ElasticSearch
关注(0)|答案(1)|浏览(296)

假设弹性Map中有一个字段,并不是所有条目都有该字段,例如,有些条目有以下值
“intvalue”:[200、201、202]“intvalue”:[200、203、204]
但有些条目没有intvalue字段
我想编写一个查询来搜索具有值的条目(例如,200202),查询包含
{“terms”:{“intvalue”:[200202],“boost”:1.0}
它只返回包含上述值的结果。
查询是否可能返回所有具有该值或不具有该字段的条目,例如,下面有4个条目
条目a:“intvalue”:[200,201]条目b“intvalue”:[200,203]条目c“intvalue”:[]条目d“intvalue”:[204,205]
然后查询{“terms”:{“intvalue”:[200202],“boost”:1.0}}应该返回条目a b,c

r1zhe5dt

r1zhe5dt1#

您可以使用布尔查询来组合现有查询和术语查询
索引数据:

{ "intvalue" : [200, 201] }
{ "intvalue" : [200, 203] }
{ "intvalue" : [] }
{ "intvalue" : [204, 205] }

搜索查询:

{
  "query": {
    "bool": {
      "should": [
        {
          "bool": {
            "must_not": {
              "exists": {
                "field": "intvalue"
              }
            }
          }
        },
        {
          "bool": {
            "must": {
              "terms": {
                "intvalue": [
                  200,
                  202
                ],
                "boost": 1.0
              }
            }
          }
        }
      ]
    }
  }
}

搜索结果:

"hits": [
      {
        "_index": "fd_cb",
        "_type": "_doc",
        "_id": "1",
        "_score": 1.0,
        "_source": {
          "intvalue": [
            200,
            201
          ]
        }
      },
      {
        "_index": "fd_cb",
        "_type": "_doc",
        "_id": "2",
        "_score": 1.0,
        "_source": {
          "intvalue": [
            200,
            203
          ]
        }
      },
      {
        "_index": "fd_cb",
        "_type": "_doc",
        "_id": "3",
        "_score": 0.0,
        "_source": {
          "intvalue": []
        }
      }
    ]

相关问题