0

How to create a query using QueryBuilders for a nested List.
Something like that:

import org.elasticsearch.index.query.QueryBuilders;
...
QueryBuilders.matchQuery(...);

I need to find a document where code equals "test" and value containing "nested" text.
Sample data in a nested class:
code = "test"
value = "my nested value"

Below are the class definitions.

import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;

@Data
@Document(indexName = "MY_DOCUMENT")
public class MyDocument {

    @Id
    @Field(type = FieldType.Keyword)
    private String id;

    @Field(type = FieldType.Nested, name = "SUB_DOC")
    private List<SubDocument> subDoc;

    ....

}
import lombok.Data;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;

@Data
class SubDocument {

    @Field(type = FieldType.Text, name = "CODE")
    private String code;

    @Field(type = FieldType.Text, name = "VALUE")
    private String value;

}

Dependencies from pom.xml

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
    <version>2.7.1</version>
</dependency>

Additionally, is it possible to create this type of query in a form acceptable to Lucene?
Something like that:

import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.AbstractQueryBuilder;
...
String stringQuery = "+SUB_DOC.VALUE:... +SUB_DOC.CODE:...";
AbstractQueryBuilder<?> q = QueryBuilders.queryStringQuery(stringQuery);

1 Answer 1

1

As you are explicitly asking for a solution using Elasticsearch QueryBuilders this is not really related to Spring Data Elasticsearch. You are just using Spring Data Elasticsearch to pass the Elasticsearch query down to the Elasticsearch client.

If you would use the Spring Data Elasticsearch classes, you could build a query like this:

var query = new CriteriaQuery(
    new Criteria("subDoc.code").is("test")
        .and("subDoc.value").contains("nested"));
var searchHits = operations.search(query, MyDocument.class);

Sign up to request clarification or add additional context in comments.

Comments

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.