Tofig Hasanov
Tofig Hasanov

Reputation: 3709

Elasticsearch scripted field with value from another document

Imagine that I have two type of documents:

There is a parent/child relationship between customers/purchases.

I need to generate a report which would contain all purchases that match certain filter criteria, but each row should also contain some lookup data from the customer doc (ex: locale of customer). I know that one of the ways to do this is to flatten data and put these fields directly into purchases doc in the first place. I would like to know if there is a way ElasticSearch could populate these fields automatically for me (maybe some scripted field lookup magic?) instead.

Upvotes: 0

Views: 1802

Answers (1)

Taras Kohut
Taras Kohut

Reputation: 2555

There is no way to access fields from parent/child using any kind of script, because it's completely different document. It would be very expensive to access parent from within the context of the child and vice versa.

Inner hits will do what you need:

PUT test
{
  "mappings": {
    "Customer": {},
    "Purchase": {
      "_parent": {
        "type": "Customer"
      }
    }
  }
}

PUT test/Customer/1
{
  "firstName": "John",
  "lastName": "Doe"
}

PUT test/Purchase/2?parent=1
{
  "price": 100
}

GET test/Purchase/_search
{
  "query":{
    "bool":{
      "must":[
        {
          "range":{
            "price":{
              "gte":10
            }
          }
        },
        {
          "has_parent":{
            "type":"Customer",
            "inner_hits":{},
            "query":{
              "match_all":{}
            }
          }
        }
      ]
    }
  }
}

Upvotes: 1

Related Questions