elasticsearch按照给定的id顺序排序

春风再美也比不上你的笑 没见过你的人不会明了

环境

  • Laravel 5.5
  • ElasticSearch 6.5

代码片段

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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
$params = [];
$length = count($conditions['id']);
foreach ($conditions['id'] as $key => $id) {
$params[] = ['id' => $id, 'score' => $length - $key];
}

$source = ['id', 'title', 'url', 'price', 'list_price', 'images', 'thumbs', 'status', 'rating', 'sort', 'reviews_amount', 'cids'];
$params = [
'index' => $index,
'type' => 'products',
'body' => [
'query' => [
'function_score' => [
'query' => [
'bool' => [
'must' => [
[
'terms' => [
'id' => $conditions['id']
]
]
]
]
],
'script_score' => [
'script' => [
'lang' => 'painless',
'params' => [
'scoring' => $params
],
'source' => "for(i in params.scoring) { if(doc['id'].value == i.id ) return i.score; } return 0;"
]
]
]
],
'_source' => $source,
],
'from' => ($page - 1) * $perPage,
'size' => $perPage,
];

$results = Searches::getEsInstance()->search($params);
$total = $results['hits']['total'];

if (empty($items = $results['hits']['hits'])) {
return [];
}

注意

不同版本的ES语法可能不同, 具体请参阅官方文档