API – Query Objects (Nested)

This article assumes that you have read API Query Objects.

At times, while performing a search, you’ll want to not only filter by entities that you are pulling for results, but also linked or nested entities. For example, maybe you want to find all loans that are insured by Allstate, but you also want to only show loans that were given to Bob. You could make a custom field on the loan that holds the customer name and in your query have the “field to match” be customFields, but that’s a waste of time, energy, and resources to keep up to date, especially when LoanPro already keeps track of the customer name. For this reason, we allow searching by nested entities.

Format

Nested entities are formatted as follows:

    "nested": {
      "path": <path here>,
      "query": {
        <query here>
      }
    }
  • <path here> – replace this with the lowercase API path to the entities (ex. Loans -> Customers becomes customers).
  • <query here> – replace this with the query for the nested entity

Example

Let’s now go over how the query could look for finding loans insured by Allstate that are given to Bob. Our query would look something like the following

{
   "query":
   {
     "bool":
     {
        "must":
        [
            {
               "match":
               {
                   "loanInsurance.companyName": "Allstate"
               }
            },
            {
                "nested":
                {
                   "path":"customers"
                   "query":
                   {
                      "bool":
                      {
                         "must":
                         [
                             {
                                "match":
                                {
                                    "firstName":"Bob"
                                }
                             }
                         ]
                      }
                   }
                }
            }
         ]
      }
   }
}

As you can see, we’re able to match against the loan insurance’s company name and the customers’ first name just fine.

Alternate Form

As stated by ElasticSearch’s documentation, there is support for accessing nested fields without having to create a nested JSON object. This is done by doing “<path>.<field name>”. The <path> is the same as the path for the nested object, and the <field name> is the name of the field for the nested object.

This means that to filter by the customer name, we could use "match":{"customer.firstName":"Bob"} instead of the method used in the above section. This does save time typing since we don’t have to create a “nested” object with its own query, but it can be less intuitive to read (it looks like we’re filtering by a loan field rather than a customer field).

Related Articles

Leave A Comment?