Array of objects max value

For a set of documents like this:
{
name: "php",
related:[
{
"count": 6806,
"name": "c#"
},
{
"count": 4080,
"name": "c"
},
{
"count": 9745,
"name": "java"
},
{
"count": 9141,
"name": "javascript"
}
]
}

I would like to get the name of the documents that match:
related.name: "javascript"
and
related.count is the max value in the array.

It's possible to do?

Thanks

Hi there,
yes it is possible. You can index your related field as nested :

{
  "mappings": {
    "my_type": {
      "properties": {
        "related": {
          "type": "nested" 
        }
      }
    }
  }
}

to find a documents that have related.name: "javascript", use nested query:

{
  "query": {
    "nested": {
      "path": "related",
      "query": {
        "match":  { "related.name": "javascript" }
       }
    }
  }
}

For finding max values, you can use nested aggregation:

"aggs" : {
    "myagg" : {
        "nested" : {
            "path" : "related"
        },
        "aggs" : {
            "max_value" : { "max" : { "field" : "related.count" } }
        }
    }
}

You can combine a search query and aggregation in a single request depending on your needs.

Hi Mayya,
Thanks for your answer.
Trying the code you provided me I get:
"aggregations": {
"myagg": {
"doc_count": 19805,
"max_value": {
"value": 1110971
}
}
}

What I wanted was to get the name of the results that match with related.name == javascript AND related.count if the maximum in the array.

So, the mapping actually is:

{
  "mappings": {
    "my_type": {
      "properties": {
       "name":{type:"keyword"},
        "related": {
          "type": "nested" ,
         "properties":{
          "name":{type:"keyword"},
          "count":{type:"long"}
         }
        }
      }
    }
  }
}

It is not very clear to me what you mean "related.count if the maximum in the array."?
Can you please provide an example of the response you expect based on your original example data?

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