简体   繁体   中英

Elasticsearch scripted field with value from another document

Imagine that I have two type of documents:

  • Customers - contains information such as region, locale, etc)
  • Purchases - contain details about individual purchases).

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.

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":{}
            }
          }
        }
      ]
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM