elasticsearch reindex和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。

注意:es默認情況下進行自動類型解析的時候,會將string類型映射成text,且子類型名稱和對應的類型都爲keyword。因此爲了保持自定義模板與默認的類型解析在這方面保持一致,上面的模板最好將子類型名稱raw改成keyword。

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這裏如何加上了refresh則會導致setting中的-1失效
{
  "source": {
    "index": "springboot-2020.04.20",
    "type":"applog",
    "size":10000
  },
  "dest": {
    "index": "springboot-testsort",
    "type":"data"
  }
}

注意:reindex的時候有個細節,就是source中的index+type的組合必須是存在的,比如這裏如果index對應的type不是applog,那麼就沒有數據。同理對於dest來說,index+type的組合也必須是存在的,否則也沒有數據。除此之外,對於dest來說,如果使用的是動態模板mapping,模板中指定了type,那麼reindex的時候dest中的type需要與模板中的保持一致。

這個複製的過程可能會持續幾分鐘。

reindex完成之後,需要修改settings,因爲沒有refresh,需要修改成1s或其他指定時間,讓它refresh到os內存,之後才能檢索到。

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

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
}

 

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