Sort Orderedit
The order
option can have the following values:
asc |
Sort in ascending order |
---|---|
desc |
Sort in descending order |
The order defaults to desc
when sorting on the _score
, and defaults to asc
when sorting on anything else.
The order
option can have the following values:
asc |
Sort in ascending order |
---|---|
desc |
Sort in descending order |
The order defaults to desc
when sorting on the _score
, and defaults to asc
when sorting on anything else.
POST index1/_search
{
"sort": [
{
"_score": {
"order": "asc"
}
}
],
"query": {
"match": {
"text": "elastic"
}
}
}
Thanks for your answer, it seems to work, so do you know how to use it in JAVA RestHighLevelClient JDK?
SearchRequest searchRequest = new SearchRequest("index1");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.matchQuery("text", "elastic"));
searchSourceBuilder.sort("_source", SortOrder.ASC);
searchRequest.source(searchSourceBuilder);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
for(List<Object> dotNameList : sorts){
String dotName = (String) dotNameList.get(0);
FieldSortBuilder fieldSortBuilder = new FieldSortBuilder(dotName);
fieldSortBuilder.unmappedType("long");
fieldSortBuilder.order("desc".equalsIgnoreCase(dotNameList.get(1).toString())
? SortOrder.DESC:SortOrder.ASC);
sourceBuilder.sort(fieldSortBuilder);
}
if (sorts.isEmpty()) {
sourceBuilder.sort("_score",SortOrder.DESC);
}
anything sort data
3 123
2 456
1 789
unmapped field data
1 789
2 456
3 123
I don't know what went wrong,it seems to be related to my use of "unmappedType",when I sort by an unmapped field, the sorting of data is opposite to that without sort.
I don't quite clear your sorting scene,this is the basic use of sort:
unmapped_type
is for index which don't have sort’s field mapping,
missing
can help you specifies how docs which are missing the sort field should be treated.
and if you have two fields to sort ,you can try as below:
POST index1/_search
{
"sort": [
{
"_score": {
"order": "asc"
}
},
{
"somefield": "desc"
}
],
"query": {
"match": {
"text": "elastic"
}
}
}
我的场景是默认没有sort条件得到data,当我使用一个新的sort字段时,正好mapping中没有这个字段,于是使用了unmappedType指定为了long,我的期望是此时和我没有sort条件时的data排序顺序一致,我看到官方文档里说的没有sort条件时默认使用asc排序,所以我想是不是把它改成默认desc就行,或者说使用了unmapped字段时如何指定此时的排序顺序呢
为什么要使用unmapped呢?一般它是用于查询多个索引,某些索引有排序字段filed1,而其他索引没有这个fields1,防止报错而使用的。你是中国人?
是啊 我看到你简书了,我们现在的场景是通过es的动态mapping自动根据传入的数据类型创建字段,但是当值为null时,es是不会在mapping中创建field的,但是这时候前端的表格sort可能会用这个字段排序,这时候会报错字段不存在,所以才找到这么一个解决方案,不知道有没有其他优雅的方式
This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.
© 2020. All Rights Reserved - Elasticsearch
Apache, Apache Lucene, Apache Hadoop, Hadoop, HDFS and the yellow elephant logo are trademarks of the Apache Software Foundation in the United States and/or other countries.