0

I have documents like these:

Doc1

{
"id": ...,
...
"articles": [
  {
    "id": "5cdd17c7e24f6e05d487b2c2#142936",
    ...
  },
  {
    "id": "5cdd17c7e24f6e05d487b2c2#226536",
    ...
  }
...
}

Doc2

{
"id": ...,
...
"articles": [
  {
    "id": "5cdd17c7e24f6e05d487b2c2#142936",
    ...
  },
  {
    "id": "5cdd17c7e24f6e05d487b2c2#226536",
    ...
  },
  {
    "id": "5cdd17c7e24f6e05d487b2c2#142965",
    ...
  }
...
}

Doc3

{
"id": ...,
...
"articles": [
  {
    "id": "5cdd17c7e24f6e05d487b2c2#142936",
    ...
  }
...
}

And I want the document exactly has the array of articles I need. For example, if my Array of article Ids is ['5cdd17c7e24f6e05d487b2c2#142936', '5cdd17c7e24f6e05d487b2c2#226536'] I only want to get the Doc1.

Now I have this query:

GET my_index/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "nested": {
            "path": "articles",
            "query": {
              "query_string": {
                "default_field": "articles.id",
                "query": "5cdd17c7e24f6e05d487b2c2#142936 AND 5cdd17c7e24f6e05d487b2c2#226536"
              }
            }
          }
        }
      ]
    }
  }
}

But with this, I get Doc1 & Doc2...

1 Answer 1

1

Assuming articles.id is of type keyword, I think this should work for you (not sure it's the most efficient way to write the query):

GET my_index/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "nested": {
            "path": "articles",
            "query": {
              "term": {
                "articles.id": "5cdd17c7e24f6e05d487b2c2#142936"
              }
            }
          }
        },
        {
          "nested": {
            "path": "articles",
            "query": {
              "term": {
                "articles.id": "5cdd17c7e24f6e05d487b2c2#226536"
              }
            }
          }
        }
      ],
      "must_not": {
        "nested": {
          "path": "articles",
          "query": {
            "query_string": {
              "default_field": "articles.id",
              "query": "NOT 5cdd17c7e24f6e05d487b2c2#142936 AND NOT 5cdd17c7e24f6e05d487b2c2#226536"
            }
          }
        }
      }
    }
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect!! Thank you!

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.