Search code examples
elasticsearchelasticsearch-aggregationelasticsearch-nested

Query elasticsearch nested field by index(order of insert)


I have an elasticsearch document with some nested objects(mapped as nested field) for example:

{
  "FirstName": "Test",
  "LastName": "Test",
  "Cost": 322.54,
  "Email": "[email protected]",
  "Vehicles": [
    {
      "Year": 2000,
      "Make": "Mazda",
      "Model": "6"
    },
    {
      "Year": 2012,
      "Make": "Ford",
      "Model": "F150"
    }
  ]
}

i am trying to do aggregations on specific index of the array, for example i want to sum the cost of documents which has Ford make but only on the first vehicle.

is it even possible at all? there is almost no information on the internet about elasticsearch nested fields and nothing about their index/order


Solution

  • It is possible to achieve what you want, but you also need to add the index order as a field inside your nested documents:

    {
      "FirstName": "Test",
      "LastName": "Test",
      "Cost": 322.54,
      "Email": "[email protected]",
      "Vehicles": [
        {
          "Year": 2000,
          "Make": "Mazda",
          "Model": "6",
          "Index": 0
        },
        {
          "Year": 2012,
          "Make": "Ford",
          "Model": "F150",
          "Index": 1
        }
      ]
    }
    

    And then you can query your index using the two conditions on Index and the Make like this:

    {
      "query": {
        "nested": {
          "path": "Vehicles",
          "query": {
            "bool": {
              "filter": [
                {
                  "match": {
                    "Vehicles.Index": 0
                  }
                },
                {
                  "match": {
                    "Vehicles.Make": "Ford"
                  }
                }
              ]
            }
          }
        }
      }
    }
    

    In this specific case, the query is not going to yield any results, as you expect.