如何在Spring Boot数据弹性搜索中搜索嵌套列表对象

时间:2020-01-22 08:17:54

标签: spring-data-elasticsearch

我的合同模型课

@Data
@Document(indexName = "contract",type = "contract")
public class Contract implements Serializable
{
    @JsonProperty("contract_number")
    @Id
    @Parent(type = "p")
    @Field(type = FieldType.Text,index =true)
    private String contract_number;

    private String startDate;

    private String endDate;

    private String supportTypeCode;

    @Field(type = FieldType.Nested,searchAnalyzer = "true")
        private List<Product> products;

我的产品分类

@Data
public class Product implements Serializable
{

    @Field(type = FieldType.Keyword)
    private String baseNumber;
    @Field(type = FieldType.Keyword)
    private String rowId;
    @Field(type = FieldType.Keyword)
    private String effectiveDate;
}

使用弹簧数据I,试图基于产品类中存在的baseNumber来获取数据。 但无法获取数据。
我尝试使用下面的JPA方法,但无法正常工作。

Optional<Contract>  findByProducts_BaseNumber(String s)

对于如何维护Contract和Product类之间的映射,我感到很困惑。

2 个答案:

答案 0 :(得分:1)

应该是

import mpl_toolkits
mpl_toolkits.__version__

findByProductsBaseNumber(String s);

documentation

中所述

答案 1 :(得分:1)

对于我来说,以下解决方案有效,我正在使用弹性7.6版Java API。

SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("products.baseNumber", baseNumber);
    searchSourceBuilder.query(matchQueryBuilder);
    searchSourceBuilder.from(0);
    searchSourceBuilder.size(5);
    SearchRequest searchRequest = new SearchRequest();
    searchRequest.indices(INDEX);
    searchRequest.source(searchSourceBuilder);
    SearchHits hits = null;
    try
    {
        hits = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT).getHits();
        final List<Contract> collect = Arrays.stream(hits.getHits()).map(
                sourceAsMap -> objectMapper.convertValue(sourceAsMap.getSourceAsMap(), Contract.class)).collect(
                Collectors.toList());
        return  collect.get(0);
    }
    catch (IOException e)
    {
        e.printStackTrace();

    }