IronWaffleMan IronWaffleMan - 1 month ago 9
Javascript Question

How to return partial doc from Elasticsearch query/filter?

I have a set of docs (let's call them

books
), which have a subset of information (let's say
editions
), for a data structure somewhat akin to this:



"book": {
"author": "A. N. Author",
"title": "Fantastic Queries and How to Index Them"
"editions": [
{
"publisher":"penguin",
"isbn": 124161256653,
"coverArtist":"Pain T Brush",
"amazonPrice":65.50
},
{
"publisher":"orbit",
"isbn": 124163526653,
"coverArtist":"Pain T Brush",
"amazonPrice":25.99
},
{
"publisher":"tor",
"isbn": 124169876353,
"coverArtist":"Pen See Il",
"amazonPrice":700.00
}
]
}





Right now with the queries I have (which search on
editions.publisher
or
editions.isbn
), I get the whole document back, including editions that don't match the query results. So, to be clear, if I search
coverArtist
for
Pain T Brush
, the data I want returned is:



"book": {
"author": "A. N. Author",
"title": "Fantastic Queries and How to Index Them"
"editions": [
{
"publisher":"penguin",
"isbn": 124161256653,
"coverArtist":"Pain T Brush",
"amazonPrice":65.50
},
{
"publisher":"orbit",
"isbn": 124163526653,
"coverArtist":"Pain T Brush",
"amazonPrice":25.99
}
]
}





Same with the other queries. If I search for a specific
isbn
, I only want its data to come back. If I set a price range of
> 500
, I'd only want the last edition (along with the author and title information, of course). And finally, if I search for
Fantastic Queries and How to Index Them
in the
title
, I want the whole doc returned, with all edition information, since I didn't specify anything edition-specific.

I'm unaware of a way to make the queries 'drill down' into particular objects in a doc, so is this even possible?

Answer

Try making the edition object into its own document, with a parent-child relationship.

https://www.elastic.co/guide/en/elasticsearch/guide/current/parent-child.html

This way you will be able to query for the exact child documents you need. If you also need the parent, each child document has a _parent property, which you can use in an _id search to return the parent doc.

You will still even be able to find the parent based on child attributes.

https://www.elastic.co/guide/en/elasticsearch/guide/current/has-child.html