chester89
chester89

Reputation: 8607

How to access document id in a script in ElasticSearch?

I'm trying to write a query that aggregates on document type. The thing is, the document type can be obtained from the document id - it's 4-5 first characters of the id, like BPR::fawL5CcPE72Wf3m93hUg2.
Here's the query I put together:

{
    "query": {
        "match_all": { }
    },
    "aggregations": {
        "by_document_type": {
            "script": {
                "script": "doc['_id'].value.substring(0, 3)",
                "order": { 
                    "_count": "desc" 
                }
            }
        }
    }
}

but it says Parse Failure [Could not find aggregator type [script] in [by_document_type]]];.

What did I do wrong?

Upvotes: 1

Views: 1555

Answers (1)

Val
Val

Reputation: 217554

You simply need to use a terms aggregation and feed your script in it:

{
  "query": {
    "match_all": {}
  },
  "aggregations": {
    "by_document_type": {
      "terms": {
        "script": "doc['_id'].value.substring(0, 3)",
        "order": {
          "_count": "desc"
        }
      }
    }
  }
}

Upvotes: 2

Related Questions