按嵌套字段搜索

时间:2020-02-24 17:59:29

标签: java spring elasticsearch

我是Elasticsearch的新手。当前,我正在尝试使用spring boot / data实现一个搜索。我有2个实体:

@Document(indexName = "my_index", type = "books")
public class Book {
    @Id
    private String id;
    @Field(type = FieldType.Text)
    private String title;
    private String author;
    private String releaseDate;

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

}

并且:

@Document(indexName = "my_index", type = "books")
public class CategoryParent {

    @Id
    private String id;
    private String name;

}

我需要按图书中的title字段和类别中的name字段进行搜索。就SQL而言,应该是这样的:

SELECT b.* FROM books b JOIN categories c WHERE c.name like '%pattern%' OR b.title like '%pattern%'

我只能使用以下代码通过book.title进行搜索:

QueryBuilder searchByCountries = QueryBuilders.wildcardQuery("title", pattern);
        final BoolQueryBuilder query = boolQuery().should(searchByCountries).should(nestedQuery("categories", wildcardQuery("categories.name", pattern), ScoreMode.None));
        final Page<Book> books = (Page<Book>) this.bookRepository.search(query);
        return books.getContent();

,但不会按category.name字段进行搜索。另外,我使用了以下代码:

        final NestedQueryBuilder searchByCategoryName = nestedQuery("categories", wildcardQuery("categories.name", pattern), ScoreMode.None);
        MatchQueryBuilder searchByTitle = matchQuery("title", pattern);
        NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
              .withQuery(searchByCategoryName)
              .withQuery(searchByTitle)
              .build();
        return bookRepository.search(searchQuery).getContent();

它返回相同的结果。如何使用OR运算符修改查询以按2个属性进行搜索?

谢谢您的建议

0 个答案:

没有答案