elasticsearch排序sort的使用

背景

使用sort的时候需要注意,如果排序字段是字符串类型的(text、string),那么会按照排序字段的值的字典顺序进行排序。

而有时候我们需要按照实际数值进行排序,这时候就需要重建索引reindex,重建索引的时候使用新的模板或指定mapping,以便将排序字段的类型修改为integer之类的数值型。

步骤

1.新建模板

PUT _template/sort_template
{
  "order": 1,
  "index_patterns": "springboot*",
  "settings": {
    "number_of_shards": 5,
    "number_of_replicas": 1
  },
  "mappings": {
    "data":{
      "dynamic_templates" : [ {  
        "keyword_field" : {  
          "match" : "*Name",  
          "match_mapping_type" : "string",  
           "mapping" : {  
            "type" : "text",
            "fields": {
              "raw": {
                "type": "keyword"
              }
            }
          }  
        }  
      }],  
      "properties": {
        "execTime":
        {
          "type":"integer"
        },
        "message":{
          "type":"text"
        }
      }
    }
  }
}

因为要对execTime字段进行排序,因此指定其类型为integer。

2.创建新索引

PUT springboot-testsort

创建一个新的索引,用于reindex。根据此索引的名字可以映射到刚才创建的模板。

3.修改索引配置

PUT springboot-testsort/_settings
{
     "number_of_replicas": 0,
     "refresh_interval": -1
}

因为原索引的数据量很大,通过修改配置来提高reindex的效率。这里将副本数设为0(禁用副本),刷新间隔为-1(禁止刷新)。具体可参考https://blog.csdn.net/laoyang360/article/details/81589459

注意:在reindex的过程中出现gateway timeout的异常,其实并不是报错,还是正常在复制数据。

4.reindex

post _reindex?slices=20&refresh
{
  "source": {
    "index": "springboot-2020.04.20",
    "type":"applog",
    "size":10000
  },
  "dest": {
    "index": "springboot-testsort",
    "type":"data"
  }
}

这个复制的过程可能会持续几分钟。

5.进行top N排序

GET springboot-testsort/data/_search
{
  "_source": ["execTime"],
  "query": {
    "bool": {
      "must":[
      {
        "exists":{
              "field": "className"
            }},
            {
        "term":{
          "className.raw":"log.utils.LogUtil"
        }
      }
    ]
    }
  }, 
    "sort" : [
        { "execTime" : {"order" : "desc"}}
    ],
    "from": 0,
    "size": 20
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章