Spring data elasticsearch multiple filters

混江龙づ霸主 提交于 2021-02-11 14:33:28

问题


Considering the mappings (messages are nested type inside channel)

@Document(indexName = "index", type = "channel")
@Data
public class Channel {

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

    @Field(type = FieldType.Date, format = DateFormat.date_hour_minute_second_millis)
    @JsonFormat(shape = JsonFormat.Shape.STRING)
    private LocalDateTime issuedTimestamp;

    @Field(type = FieldType.Text)
    private String clientUsername;

    @Field(type = FieldType.Nested, includeInParent = true)
    private List<Message> messages;

}

@Data
public class Message {

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

    @Field(type = FieldType.Date, format = DateFormat.date_hour_minute_second_millis)
    @JsonFormat(shape = JsonFormat.Shape.STRING)
    private LocalDateTime issuedTimestamp;

    @Field(type = FieldType.Text)
    private String body;

}

I want to retrieve all the channels for a certain customer together with all the messages that contain in their body attribute all the words (or part of the words) inside a "searchString" parameter that can contain whitespaces.

I have the following code, which seems to work fine so far, but since i'm new to elastic search are there any issues with the below code or is there a better option to achieve this (for instance, from a performance perspective) ?

BoolQueryBuilder query = QueryBuilders.boolQuery()
                    .filter(QueryBuilders.termsQuery("clientUsername", userId));

List<String> wordsToSearchFor = Arrays.asList(searchString.split(" "));
                for (String word : wordsToSearchFor) {
                    query.filter(QueryBuilders.regexpQuery("messages.body", ".*"+word+".*"));
                }
Query searchQuery = new NativeSearchQueryBuilder().withQuery(query).build();
SearchHits<Channel> channels = elasticsearchRestTemplate.search(searchQuery, Channel.class, IndexCoordinates.of("index"));

EDIT : and if i want to retrieve only the nested Message objects that are compliant with the regexpQuery is there any way to do it from the spring data elasticsearch ? I believe this would be possible with the help of inner hits but this will only be available in spring data elasticsearch 4.1 (Getting InnerHits Result from SearchHits Class at Spring Data Elastic Search 4.0.0)

来源:https://stackoverflow.com/questions/63953648/spring-data-elasticsearch-multiple-filters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!