我使用的是org.springframework.data:spring-data-elasticsearch:4.1.0和elasticsearch 7.8.1。
我有一个需求,我需要查找多个属性的部分搜索。我已经实现了通配符bool查询,它工作得很好,除了它不能查找空格。
下面是我的实际查询:
GET /maintenance_logs/_search
{
"query": {
"bool": {
"must": [
{
"term": {
"vinNumber.keyword": "DH34ASD7SDFF84742"
}
},
{
"term": {
"organizationId": 1
}
}
],
"minimum_should_match": 1,
"should": [
{
"wildcard": {
"dtcCode": {
"value": "*Cabin*"
}
}
},
{
"wildcard": {
"subSystem": {
"value": "*Cabin*"
}
}
},
{
"wildcard": {
"maintenanceActivity": {
"value": "*Cabin*"
}
}
},
{
"wildcard": {
"description": {
"value": "*Cabin*"
}
}
}
]
}
}
}
这是我的搜索请求:
public static SearchRequest buildSearchRequest(final String indexName,
final SearchRequestDTO dto,
final String vinNumber,
final Integer organizationId, Pageable pageable) {
try {
final int page = pageable.getPageNumber();
final int size = pageable.getPageSize();
final int from = page <= 0 ? 0 : pageable.getPageSize();
SearchRequest searchRequest = new SearchRequest(indexName);
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
final QueryBuilder vinQuery = QueryBuilders.termQuery("vinNumber.keyword", vinNumber);
final QueryBuilder orgIdQuery = QueryBuilders.termQuery("organizationId", organizationId);
boolQueryBuilder.must(vinQuery);
boolQueryBuilder.must(orgIdQuery);
boolQueryBuilder.minimumShouldMatch(1);
boolQueryBuilder.should(QueryBuilders.wildcardQuery("dtcCode", "*" + dto.getSearchTerm() + "*"));
boolQueryBuilder.should(QueryBuilders.wildcardQuery("subSystem", "*" + dto.getSearchTerm() + "*"));
boolQueryBuilder.should(QueryBuilders.wildcardQuery("maintenanceActivity", "*" + dto.getSearchTerm() + "*"));
boolQueryBuilder.should(QueryBuilders.wildcardQuery("description", "*" + dto.getSearchTerm() + "*"));
searchSourceBuilder.query(boolQueryBuilder);
searchSourceBuilder
.from(from)
.size(size)
.sort(SortBuilders.fieldSort("statsDate")
.order(SortOrder.DESC));
searchRequest.source(searchSourceBuilder);
return searchRequest;
} catch (final Exception e) {
e.printStackTrace();
return null;
}
}
这工作正常,但我无法搜索字符串,如"机舱压力"
如果您希望能够搜索多个令牌值,如"机舱压力"使用">座舱压力&"通配符查询可找到;您需要在映射中将其定义为类型为keyword
。
通配符搜索单个项匹配通配符表达式,以及"机舱压力";默认情况下分为两个术语,"one_answers"pressure".
在Spring Data Elasticsearch中,这样做的方法是使用@Field(type = FieldType.Keyword
,但是您要么需要删除并重新创建索引以应用新的映射,要么需要创建一个新的索引并将现有的索引重新索引到新的索引中。这是因为索引映射不能更新,并且在您现有的索引中,该类型默认定义为text
。
如果你储存了"舱内压力"作为一个术语-类型keyword
-不要忘记,这将是一个不同的东西,与"机舱压力"。关键字没有标准化,因此大小写差异很重要。