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
}

 

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