Subset in an array

Hi everyone,

Thanks for reading.

Here's my problem. I have an array with numbers on each document as such:

Document 1: [1, 2, 3]
Document 2: [1, 4]
Document 3: [6,12,2]

I want to query my documents and find those documents that has subsets of my array: [1, 2, 3, 5, 10]. In this case only document 1 should be matched.

I don't want to run a script like: Subsets

Thanks again for reading - I hope you have some inputs.

Hi @surendra_gandham,

I think it would be interesting for this situation to try the term_set query.

You would have to add a field with the total of items in the array of each document and then use the term_set query along with this field. https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-terms-set-query.html

It would be something like the example below:

PUT my_index/_doc/1
{
  "values": [1, 2, 3],
  "itemsCount": 3
}

PUT my_index/_doc/2
{
  "values": [1, 4],
  "itemsCount": 2
}

PUT my_index/_doc/3
{
  "values": [6, 12, 2],
   "itemsCount": 3
}
GET my_index/_search
{
  "query": {
    "terms_set": {
      "values": {
        "terms": [1, 2, 3, 5, 10],
        "minimum_should_match_field": "itemsCount"
      }
    }
  }
}

Thanks, @jessepeixoto.
I agree with you, but I am going with Minimum should match script for now. Meaning on the go I am going to calculate the length of existing array field.

1 Like

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.