I am using spring-data-elasticsearch (4.0.1) and elasticsearch together to query documents. I'd like to do nested queries on nested documents with Criteria, I annotated the entities classes but cannot do the query with the criteria refering to nested field.
{
"user" : {
"mappings" : {
"properties" : {
"contacts" : {
"type" : "nested",
"properties" : {
"description" : {
"type" : "text"
},
"id" : {
"type" : "long"
}
}
},
"id" : {
"type" : "long"
},
"name" : {
"type" : "text"
}
}
}
}
}
{
"took" : 5,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 1,
"relation" : "eq"
},
"max_score" : 1.0,
"hits" : [
{
"_index" : "user",
"_type" : "_doc",
"_id" : "MgHFrXUBYAZ",
"_score" : 1.0,
"_source" : {
"id" : 1,
"name" : "Peter",
"contacts" : [
{
"id" : 1,
"description" : "foo"
},
{
"id" : 2,
"description" : "bar"
}
]
}
}
]
}
}
@Document(indexName = "user", createIndex = false)
public class User {
@Id
private Long id;
@Field(type = FieldType.Nested)
private List<Contacts> contactos;
}
public class Contacts {
@Field(type = FieldType.Long)
private Long id;
@Field(type = FieldType.Text)
private String description;
}
Criteria criteria = new Criteria("contacts.id").is(1);
CriteriaQuery query = new CriteriaQuery(criteria).setPageable(pageable);
SearchHits<User> searchHits = this.elasticsearchRestTemplate.search(query, User.class);
I´m not getting any results, what am i doing wrong?
You may want to implement this nested query using the NativeSearchQueryBuilder from Spring Data. Here is a snippet about how it would look like:
QueryBuilder builder = nestedQuery("contactos", boolQuery().must(termQuery("contacts.id", 1)));
SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(builder).build();
List<User> users = elasticsearchTemplate.queryForList(searchQuery, User.class);