Filtering documents by an unknown value of a field


I'm trying to create a query to filter my documents by one (can be anyone) value from a field (in my case ""). The point is that I don't know previously the unique values of this field. I need found these and choose one to be used in the query.

I had tried the below query using a painless script, but I have not been able to achieve the goal.

      "sort" : [{"@timestamp": "desc"}, {"": "asc"}],
      "query": {
        "bool": {
          "filter": {
            "script": {
              "script": {
                "source": """
                  String k = doc[''][0];
                  return doc[''].value == k;
                "lang": "painless"

I'll appreciate if any can help me improving this idea of suggesting me a new one.

Is it that you want to retrieve unique values from this field, and maybe present users with an option to select one of the values? If that's what you want to do, and assuming that is a keyword field, I would recommend using 2 queries:

  1. Use a terms aggregation on the field to retrieve unique values across all docs (optionally using a query to limit which docs match, like a time range)
  2. Perform a second query with a term query using one of the values selected from the resulting aggregations of the first query.

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