我们有一个包含以下字段的索引,需要通过搜索索引中所有文本和关键字映射字段的数据来向用户提供自动建议
{
"settings": {
"number_of_shards": 1,
"number_of_replicas": 1,
"analysis": {
"filter": {
"autocomplete_filter": {
"type": "edge_ngram",
"min_gram": 1,
"max_gram": 20
}
},
}
},
"mappings": {
"properties": {
"id": {
"type": "text"
},
"title": {
"type": "text"
},
"date": {
"type": "date",
"format": "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
},
"subject": {
"type": "text"
},
"title_suggest": {
"type": "completion",
"analyzer": "simple",
"preserve_separators": true,
"preserve_position_increments": true,
"max_input_length": 50
},
"subject_suggest": {
"type": "completion",
"analyzer": "simple",
"preserve_separators": true,
"preserve_position_increments": true,
"max_input_length": 50
}
"fieldOr": {
"type": "text"
},
"fieldsTa": {
"type": "text"
},
"notes": {
"type": "text"
},
"fileDocs": {
"type": "nested",
"properties": {
"fileName": {
"type": "text",
"analyzer": "autocomplete",
"search_analyzer": "standard"
},
"fileContent": {
"type": "text",
"analyzer": "autocomplete",
"search_analyzer": "standard"
},
"docType": {
"type": "keyword"
},
"opinionId": {
"type": "integer"
}
}
},
"fileMeta": {
"type": "nested",
"properties": {
"url": {
"type": "text"
},
"name": {
"type": "text"
}
}
}
}
}
}
我尝试过"完成建议",但它适用于1个字段。我已经在索引中创建了两个带有*-submit的字段,并尝试使用completionSuggest 创建suggest
SuggestBuilders.completionSuggestion("my_index_suggest").text(input);
但它只支持1个字段。我将ES 7.6.3与Java HighLevel Rest Client一起使用,它适用于1个字段。我需要做哪些更改来支持多个领域。这可以通过JSON搜索实现吗?如果是,那么我可以使用Xcontentbuilder创建一个json,并执行自动建议?
使用copy_to,将所有需要的字段复制到一个字段中,并在上面执行您的建议。
copy_to文档中的示例是
PUT my_index
{
"mappings": {
"properties": {
"first_name": {
"type": "text",
"copy_to": "full_name"
},
"last_name": {
"type": "text",
"copy_to": "full_name"
},
"full_name": {
"type": "text"
}
}
}
}
为了便于说明,我使用了自己的索引映射,它只有两个字段name
和address
,我将在这两个字段上使用前缀进行自动完成查询,您可以类似地包括更多字段。
索引映射
{
"employee": {
"mappings": {
"properties": {
"address": {
"type": "text"
},
"name": {
"type": "text"
}
}
}
}
}
使用Rest高级客户端搜索查询
public SearchResponse autosuggestSearch() throws IOException {
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
BoolQueryBuilder qb = QueryBuilders.boolQuery();
PrefixQueryBuilder namePQBuilder = QueryBuilders.prefixQuery("address", "usa");
PrefixQueryBuilder addressPQBuilder = QueryBuilders.prefixQuery("address", "usa");
qb.should(namePQBuilder);
qb.should(addressPQBuilder); //Similarly add more fields prefix queries.
sourceBuilder.query(qb);
SearchRequest searchRequest = new SearchRequest("employee").source(sourceBuilder);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
System.out.println("Search JSON query n" + searchRequest.source().toString()); //Generated ES search JSON.
return searchResponse;
}
对于本例,生成的搜索JSON
{
"query": {
"bool": {
"should": [
{
"prefix": {
"address": {
"value": "usa",
"boost": 1.0
}
}
},
{
"prefix": {
"address": {
"value": "usa",
"boost": 1.0
}
}
}
],
"adjust_pure_negative": true,
"boost": 1.0
}
}
}
}