Search code examples
elasticsearchelastic-stackelasticsearch-dsl

Search in object array for mutiple conditions in elastic search document


I hope you can help me to find the solution, my problem is: I have a list of documents indexed in my index like

{
 "title" : "document 1",
 "status" 2,
 "documentParts" : [{ "partTitle": "part 1",
                      "typePart" : 1,
                      "statusPart" : 2},
                    { "partTitle": "part 2",
                      "typePart" : 2,
                      "statusPart" : 1}]
 

},
{
 "title" : "document 2",
 "status" 2,
 "documentParts" : [{ "partTitle": "part 2",
                      "typePart" : 2,
                      "statusPart" : 2}]
 

},
{
 "title" : "document 3",
 "status" 2,
 "documentParts" : [{ "partTitle": "part 1",
                      "typePart" : 1,
                      "statusPart" : 1},
                    { "partTitle": "part 2",
                      "typePart" : 2,
                      "statusPart" : 2}]
 

},
{
 "title" : "document 4",
 "status" 2,
 "documentParts" : [{ "partTitle": "part 1",
                      "typePart" : 1,
                      "statusPart" : 1},
                    { "partTitle": "part 2",
                      "typePart" : 2,
                      "statusPart" : 1}]
> 

I want the documents that have the "documentParts" with "typePart = 1" and "statusPart = 1" In te same item of "documentParts" array.
The wished documents are "document 3" and "document 4" but when I make the following I obtain the "document 1", "document 3", "document 4" because the query search in any element of array, not in the same array item.

My query is:

{
  "from": 0,
  "size": 10,  
  "query": {
    "bool": {
      "must": [
        {
          "term": {
            "status": {
              "value": 2
            }
          }
        },
        {
          "terms": {
            "documentParts.typePart": [ 1 ],
            "_name": "documentPartFilter"
          }
        },
        {
          "terms": {
            "documentParts.statusPart": [ 1 ],
            "_name": "documentPartStatusFilter"
          }
        }
      ]
    }
  }
}

What is the way to search in the same array item?

This query retrieves all the objects in a array that matches at least one condition. Expected result should be those objects in array that all fullfils all conditions.


Solution

  • You need to use the nested field type.

    The nested type is a specialised version of the object data type that allows arrays of objects to be indexed in a way that they can be queried independently of each other.