2

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?

1 Answer 1

2

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);
Sign up to request clarification or add additional context in comments.

2 Comments

Isn´t there any way to do it by using Criteria? Criteria fits better my previous code. In any case thanks for your answer.
In 4.0.1 spring-data version, elasticsearchRestTemplate.queryForList(...) is deprecated, any other suggestion? Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.