[英]How to specify a newer version of Elasticsearch in spring-boot
[英]How to return distance and all fields using elasticsearch and spring-boot (springframework.data.elasticsearch)
我找到了一种使用 elasticsearch 查询获取数据的方法。 但我目前的问题是在 spring 引导查询中翻译它。
我的查询如下:
{
"from": 0,
"size": 10,
"query": {
"bool": {
"should": [
{
"constant_score": {
"filter": {
"term": {
"my_field": "my_value"
}
},
"boost": 10
}
},
{
"constant_score": {
"filter": {
"term": {
"my_field": "my_value"
}
},
"boost": 8
}
}
],
"filter": [
{
"terms": {
"my_array_field": [
"first_value",
"second_value"
]
}
},
{
"geo_distance": {
"distance": "10km",
"location": {
"lat": 40,
"lon": 2
}
}
}
]
}
},
"script_fields": {
"distance": {
"script": "doc['location'].arcDistance(40, 2) / 1000"
}
},
"_source": true,
"sort": [
{
"_score": "desc"
}
]
}
存储在索引中的所有文档都有一个字段location
,类型定义为geo_point
我的问题是:
如何使用 spring-boot 翻译返回距离的script_fields
。
我当前的代码是:
BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
NativeSearchQuery nativeSearchQuery = new NativeSearchQueryBuilder()
.withQuery(boolQueryBuilder)
.withPageable(PageRequest.of(page, size))
.build();
elasticsearchOperations.search(nativeSearchQuery, MyIndexedDocument.class);
我尝试从这里使用 ScriptField 并在这里看到了一个示例,但目前没有找到任何解决方案。
_source
字段。 是否可以使用NativeSearchQuery
对其进行精确化?作为解决方法回答
如果有人有更好的答案,我会在没有任何经过验证的答案的情况下提出问题。
如果这是一个与某人相关的问题,我最终选择使用地理距离排序来处理距离返回。
查询是这样的:
{
"from": 0,
"size": 10,
"query": {
"bool": {
"should": [
{
"constant_score": {
"filter": {
"term": {
"my_field": "my_value"
}
},
"boost": 10
}
},
{
"constant_score": {
"filter": {
"term": {
"my_field": "my_value"
}
},
"boost": 8
}
}
],
"filter": [
{
"terms": {
"my_array_field": [
"first_value",
"second_value"
]
}
},
{
"geo_distance": {
"distance": "10km",
"location": {
"lat": 40,
"lon": 2
}
}
}
]
}
},
"sort" : [
{ "_score": "desc"},{
"_geo_distance": {
"location": {
"lat": 40,
"lon": 2
},
"order": "asc",
"unit": "km",
"mode": "min",
"distance_type": "arc",
"ignore_unmapped": true
}
}
]
}
所以我可以获得我的距离作为回报,但不是作为content的字段,而是作为sortvalues中的值
使用spring数据elasticsearch:
BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
ScoreSortBuilder scoreSortBuilder = new ScoreSortBuilder();
GeoDistanceSortBuilder geoDistanceSortBuilder = new GeoDistanceSortBuilder("location", Double.parseDouble(location.getLatitude()), Double.parseDouble(location.getLongitude()));
geoDistanceSortBuilder.unit(DistanceUnit.KILOMETERS);
geoDistanceSortBuilder.ignoreUnmapped(true);
geoDistanceSortBuilder.sortMode(SortMode.MIN);
geoDistanceSortBuilder.order(SortOrder.ASC);
NativeSearchQuery nativeSearchQuery = new NativeSearchQueryBuilder()
.withQuery(boolQueryBuilder)
.withPageable(PageRequest.of(page, size))
.withSort(scoreSortBuilder)
.withSort(geoDistanceSortBuilder)
.build();
elasticsearchOperations.search(nativeSearchQuery, MyIndexedDocument.class);
你可以使用注解@ScriptedField
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.