Aggregate count and max per document query

Hi @dimalini welcome back!

Perhaps you'll find this solution helpful for your use case. I used it on a sample index similar to the one you mentioned above and it seemed to work fine. Although there are considerations to keep in mind that are mentioned in the solution link.

Documents

 "hits": {
    "total": {
      "value": 3,
      "relation": "eq"
    },
    "max_score": 1,
    "hits": [
      {
        "_index": "system_logs",
        "_id": "1",
        "_score": 1,
        "_source": {
          "name": "windows",
          "messages": [
            "404",
            "500",
            "200"
          ]
        }
      },
      {
        "_index": "system_logs",
        "_id": "2",
        "_score": 1,
        "_source": {
          "name": "mac",
          "messages": [
            "404",
            "500",
            "200",
            "404",
            "500",
            "200"
          ]
        }
      },
      {
        "_index": "system_logs",
        "_id": "3",
        "_score": 1,
        "_source": {
          "name": "macair",
          "messages": [
            "404",
            "500",
            "200",
            "404",
            "500",
            "200",
            "404",
            "500",
            "200"
          ]
        }
      }
    ]
  }
}

Query

GET system_logs/_search
{
  "_source": {
    "excludes": [ "messages" ]
  },
  "script_fields": {
    "number_of_messages": {
      "script": {
        "source": "params['_source'].messages.length"
      }
    }
  }
}

Result

"hits": {
    "total": {
      "value": 3,
      "relation": "eq"
    },
    "max_score": 1,
    "hits": [
      {
        "_index": "system_logs",
        "_id": "1",
        "_score": 1,
        "_source": {
          "name": "windows"
        },
        "fields": {
          "number_of_messages": [
            3
          ]
        }
      },
      {
        "_index": "system_logs",
        "_id": "2",
        "_score": 1,
        "_source": {
          "name": "mac"
        },
        "fields": {
          "number_of_messages": [
            6
          ]
        }
      },
      {
        "_index": "system_logs",
        "_id": "3",
        "_score": 1,
        "_source": {
          "name": "macair"
        },
        "fields": {
          "number_of_messages": [
            9
          ]
        }
      }
    ]
  }