I am new to ELastic Search.
Data in Elastic search is in Parent-Child Model.I want to perform search in this data using java api.
parent type contains author details and child type contains book details like book name,book publisher, book category.
While performing a search on child details,I need to get the parent details also and vice versa. Sometimes search conditions will be on parent type as well as child. eg search for books written by author1
and type Fiction
.
How can i implement this in java? I have referred the elastic search documentation but not able to get a solution
Please help
I've done something similar with "spring-data-elasticsearch" library. There are heaps of samples available on their test suite.
Follow this link on git : https://github.com/spring-projects/spring-data-elasticsearch/blob/master/src/test/java/org/springframework/data/elasticsearch/NestedObjectTests.java
First set up your index with the
parent/child
mapping. In the mapping below I have also added a untokenized field forcategories
so you can execute filter queries on that field. (For creating the index and documents I'm using the JSON API not the Java API as that was not part of the question.)Create some
author
documents:Create some
book
documents, specifying the relationship betweenbook
andauthor
in the request.The Java class below executes 3 queries:
books
that have the term 'book' in the title and return theauthors
.authors
that have the terms 'jon doe' in the name and return thebooks
.books
written by 'jane smith' and that are of type Fiction.You can run the class from the command line, or import into Eclipse and right click on the class and select 'Run As > Java Application'. (You'll need to have the Elasticsearch library in the classpath.)
You can use Parent-Child documents for this.
Let's create an index
bookstore
with simple mappings for author documents and book documents. You can add more fields as per your requirements. See this for more information about indexing parent/child documents.Now let's add two authors:
Now let's add two books of author
author1
:Now let's add two books of author
author2
:We're done indexing documents. Now let's start searching.
Search all books authored by author
author1
(Read more about this here)Search the author of book
book11
(Read more about this here)Search for books named
book12
and authored byauthor1
. You need to usebool
queries to achieve this. (There can be a better example for this scenario with more fields in the documents)