Filtering documents by an unknown value of a field

340 views Asked by At

I'm trying to create a query to filter my documents by one (can be anyone) value from a field (in my case "host.name"). 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"}, {"host.name": "asc"}],
      "query": {
        "bool": {
          "filter": {
            "script": {
              "script": {
                "source": """
                  String k = doc['host.name'][0];
                  return doc['host.name'].value == k;
                """,
                "lang": "painless"
              }
            }
          }
        }
      }

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

1

There are 1 answers

0
Joe - Check out my books On

TL;DR you can't.

The script query context operates on one document at a time and so you won't have access to the other docs' field values. You can either use a scripted_metric aggregation which does allow iterating through all docs but it's just that -- an aggregation -- and not a query.

I'd suggest to first run a simple terms agg to figure out what values you're working with and then build your queries accordingly.