php elsearch autocomplete

PHP+Eleasticsearch 实现自动补全

1. 创建索引

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
public function createIndex() {
$params = [
'index' => 'auto_complete_shop',
'body' => [
'settings' => [
'number_of_shards' => 1,
'analysis' => [
'filter' => [
'autocomplete_filter' => [
'type' => 'edge_ngram',
'min_gram' => 1,
'max_gram' => 20
]
],
'analyzer' => [
'autocomplete' => [
'type' => 'custom',
'tokenizer' => 'standard',
'filter' => [
'lowercase', 'autocomplete_filter'
]
]
]
]
],
'mappings' => [
'goods' => [
'_source' => [
'enabled' => true
],
'properties' => [
'name' => [
'type' => 'string',
'analyzer' => 'autocomplete',
'search_analyzer' => 'standard'
]
]
]
]
]
];

$result = $this->client->indices()->create($params);

return json_encode($result);
}

2. 批量索引文档

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
public function indexGoods() {
$goods = db('goods')->field('id, name, category_id, goods_no, pro_no, depot, brand_id, sell_price, market_price, cost_price, create_time, store_nums, warning_line')->select();

$params = ['body' => []];

if ($goods !== false) {
foreach ($goods as $k => $good) {
$params['body'][] = [
'index' => [
'_index' => 'auto_complete_shop',
'_type' => 'goods',
'_id' => $good['id']
]
];

$params['body'][] = [
'name' => $good['name'],
'categoryId' => $good['category_id'],
'goodsNo' => $good['goods_no'],
'proNo' => $good['pro_no'],
'depot' => $good['depot'],
'brandId' => $good['brand_id'],
'sellPrice' => $good['sell_price'],
'marketPrice' => $good['market_price'],
'costPrice' => $good['cost_price'],
'createTime' => $good['create_time'],
'storeNums' => $good['store_nums'],
'warningLine' => $good['warning_line']
];

if ($k % 1000 == 0) {
$responses = $this->client->bulk($params);
$params = ['body' => []];
unset($responses);
}
}

if (!empty($params['body'])) {
$responses = $this->client->bulk($params);
return json_encode($responses);
}

return json_encode(['status' => 'success']);
}

return json_encode(['status' => 'faild']);
}

3. 自动补全接口

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
public function autoComplete() {
$search = input('get.search');

$params = [
'index' => 'auto_complete_shop',
'type' => 'goods',
'body' => [
'query' => [
'match' => [
'name' => $search
]
]
]
];

$response = $this->client->search($params);

if (isset($response['hits']['hits']) && count($response['hits']['hits']) > 0) {
$result = [];

$hits = $response['hits']['hits'];
foreach ($hits as $k => $v) {
$result[$k]['name'] = $v['_source']['name'];
// array_push($result, $v['_source']['name']);
}

return json_encode($result);
}
return json_encode([]);
}