1

given that there is a field in the elastic mapping, not all the entries have thie field, for example, some entries have following value

"intvalue" : [200, 201, 202] "intvalue" : [200, 203, 204]

but some entries do not have intvalue field

I want to write a query to search the entries having values(for example, 200, 202), the query contains

{"terms":{"intvalue":[200,202],"boost":1.0}}

it will only return the results containing the value as example above.

is it possible that the query can return all the entries having the value or do not have the field, for example, I have 4 entries below

Entry A: "intvalue" : [200, 201] Entry B "intvalue" : [200, 203] Entry C "intvalue" : [] Entry D "intvalue" : [204, 205]

then the query {"terms":{"intvalue":[200,202],"boost":1.0}} shoudl return Entry A B, C

2
  • did you get a chance to go through my answer, looking forward to get feedback from u Commented Aug 20, 2020 at 8:54
  • its been a long time. It would be great if you can accept and upvote my answer if it helped you resolve your issue :) Commented Sep 24, 2020 at 6:42

1 Answer 1

2

You can use Boolean query to combine Exists query and Terms Query

Index Data:

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

Search Query:

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

Search Result:

"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": []
        }
      }
    ]
Sign up to request clarification or add additional context in comments.

1 Comment

@Jacky Xi glad to hear that :) Can u please accept and upvote the answer as well, as this helped u to resolve your issue :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.