In Elasticsearch, you can filter results based on the content of inner hits using the nested or has_child queries. Inner hits allow you to retrieve additional matching documents that are related to the parent document. Filtering based on inner hits allows you to control which parent documents are returned based on the properties of their inner hits.

Here's an example of how you can filter results based on inner hits using the nested query:

Suppose you have an index named "products" with documents that contain nested objects for reviews. Each review has a "rating" field.

  1. Mapping example:
json
PUT /products { "mappings": { "properties": { "name": { "type": "text" }, "reviews": { "type": "nested", <--- This defines "reviews" as a nested field "properties": { "rating": { "type": "integer" } // Add other review properties here } } } } }
  1. Example documents:
json
POST /products/_doc/1 { "name": "Product 1", "reviews": [ { "rating": 4 // Other review properties here }, { "rating": 5 // Other review properties here } ] } POST /products/_doc/2 { "name": "Product 2", "reviews": [ { "rating": 3 // Other review properties here }, { "rating": 4 // Other review properties here } ] }
  1. Query to filter products based on the rating of their reviews:
json
POST /products/_search { "query": { "nested": { "path": "reviews", <--- The nested path where inner hits are located "query": { "range": { "reviews.rating": { "gte": 4 <--- Filter condition for the rating of inner hits } } }, "inner_hits": {} <--- To retrieve the matching reviews inside the inner_hits object } } }

In this example, the query will retrieve products where at least one review has a rating of 4 or higher. The result will include inner hits for the reviews that meet the filtering criteria.

You can adjust the query according to your specific requirements and the structure of your documents. Additionally, if you have a has_child relationship instead of a nested relationship, you can use the has_child query to achieve similar filtering based on inner hits.

Have questions or queries?
Get in Touch