0

I have following mapping:

{
  "test_index" : {
    "mappings" : {
      "test_type" : {
        "properties" : {
          "field1" : {
            "type" : "string"
          },
          "field2" : {
            "type" : "string"
          },
          "items" : {
            "type" : "nested",
            "properties" : {
              "nested_field1" : {
                "type" : "string"
              },
              "nested_field2" : {
                "type" : "string"
              }            
            }
          }
        }
      }
    }
  }
}

With search results I want to get total nested items inside the results structure:

{
  "hits": {
    "total": 2,
    "max_score": 1.0,
    "hits": [
      {
        "_index": "test_index",
        "_type": "test_type",
        "_id": "AWfAc79wljtimCd5JZlJ",
        "_score": 1.0,
        "_source": {
          "field1": "Some string 1",
          "field2": "Some string 2",
          "items": [
            {
              "nested_field1": "Some val1",
              "nested_field2": "Some val2"
            }
          ],
          "totalItems": 1
        }
      },
      {
        "_index": "test_index",
        "_type": "test_type",
        "_id": "AZxfc79dtrt878xx",
        "_score": 1.0,
        "_source": {
          "field1": "Some string 3",
          "field2": "Some string 4",
          "items": [
            {
              "nested_field1": "Some val3",
              "nested_field2": "Some val4"
            },
            {
              "nested_field1": "Some val5",
              "nested_field2": "Some val6"
            }
          ],
          "totalItems": 2
        }
      }
    ]
  }
}

Can I achieve this via aggregations?

Aman Garg
  • 3,122
  • 4
  • 24
  • 32
Bounce
  • 2,066
  • 6
  • 34
  • 65

1 Answers1

2

Since you have had the great idea to also store the totalItems field at the root level you could just sum up that field and you'd get the number of nested items:

{
  "query": {
    "match_all": {}
  },
  "aggs": {
    "total_items": {
      "sum": {
        "field": "totalItems"
      }
    }
  }
}
Val
  • 207,596
  • 13
  • 358
  • 360