Elasticsearch脚本排序

由于自己要自定义score, 所以才会使用script来写复杂的sort

javascript script 排序

1
bin/plugin -install elasticsearch/elasticsearch-lang-javascript/1.4.0
  • 写js脚本

在你的配置目录下新建文件scripts/products/sort.js, 我的配置目录是/etc/elasticsearch,简单实例:

1
2
3
(function(){
  doc._score.value + doc.likes.value
})()
  • 查询
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
curl -XGET 'http://localhost:9200/products/_search?pretty' -d '{
  "query": {
    "custom_score": {
      "script": "global_product",
      "query": {
        "filtered": {
          "filter": {
            "and": [
              {
                "term": {
                  "_type": "product"
                }
              }
            ]
          }
        }
      }
    }
  },
  "sort": [
    {
      "_score": "desc"
    }
  ]
}'

products_sort: products是目录sort脚本文件名

native script 排序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
curl -X GET 'http://localhost:9200/products/_search?pretty' -d '{
  "query": {
    "custom_score": {
      "script": "productSort",
      "lang": "native",
      "query": {
        "filtered": {
          "filter": {
            "and": [
              {
                "term": {
                  "_type": "product"
                }
              }
            ]
          }
        }
      }
    }
  },
  "sort": [
    {
      "_score": "desc"
    }
  ]
}'

单机做测试,js与native排序性能方面有差距同样的5W数据,比较一下查询速度: js:70ms, native: 20ms

Comments

Copyright © 2017 kaka