Reputation: 73
My contract model class
@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;
My product class
@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;
}
Using spring data I,m trying to fetch data based on baseNumber
which is present in product class.
But not able to get data.
I tried using below JPA Method but it is not working.
Optional<Contract> findByProducts_BaseNumber(String s)
I am quite confused about how to maintain a mapping between Contract and Product class.
Upvotes: 3
Views: 2295
Reputation: 73
For me below solution worked I'm using elastic 7.6 version 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();
}
Upvotes: 2
Reputation: 19431
That should be
findByProductsBaseNumber(String s);
or
findByProducts_BaseNumber(String s);
as explained in the documentation
Upvotes: 2