16. Suggest¶
Suggests similar looking terms based on a provided text by using a suggester. Parts of the suggest feature are still under development.
Save a suggestion to index
1<?php
2
3$elastic = new ElasticSearch();
4
5$suggest = $elastic->suggest()
6 ->index('my-index')
7 ->id(1)
8 ->input([
9 [
10 'input' => 'My name is Şêro',
11 'weight' => 25
12 ]
13 ])
14 ->save();
Search with suggest
1<?php
2
3$suggest = $elastic->suggest()
4 ->index('my-index')
5 ->name('my-index-suggest')
6 ->text('My name is ') // it returns "My name is Şêro"
7 ->completion([
8 'field' => 'suggest',
9 'skip_duplicates' => true
10 ])
11 ->search();
12
13return $suggest;
You can use multiple suggestion
1<?php
2
3$suggest = $elastic->suggest()
4 ->index('my-index')
5 ->name('my-index-suggest')
6 ->text('My name is ') // it returns "My name is Şêro"
7 ->completion([
8 'field' => 'suggest',
9 'skip_duplicates' => true
10 ])
11 ->addSuggest(function(){
12 return $this->index('my-index')
13 ->name('my-index-suggest-2')
14 ->text('Music')
15 ->completion([
16 'field' => 'suggest',
17 'skip_duplicates' => true,
18 'fuzzy' => [
19 'fuzziness' => 1
20 ]
21 ])
22 ->getMap();
23 })
24 ->addSuggest(function(){
25 return $this->index('my-index')
26 ->name('my-index-suggest-3')
27 ->text('Music')
28 ->completion([
29 'field' => 'suggest',
30 'skip_duplicates' => true
31 ])
32 ->getMap();
33 })
34 ->search();
35
36return $suggest;
Other functions you can use for suggestion
1<?php
2
3$suggest = $elastic->suggest()
4 ->index('my-index')
5 ->name('product-suggestion')
6 ->text('tring out Elasticsearch')
7 ->term(['name' => 'message'])
8 ->input([ "Nevermind", "Nirvana" ])
9 ->weight(34)
10 ->prefix('nir')
11 ->regex('regex')
12 ->completion([
13 'field' => 'suggest',
14 'size' => 10,
15 'contexts' => [
16 'place_type' => [
17 [
18 'context' => 'cafe'
19 ],
20 [
21 'context' => 'restaurants',
22 'boost' => 2
23 ]
24 ]
25 ]
26 ])
27 ->contexts([
28 [
29 "name" => "place_type",
30 "type" => "category"
31 ],
32 [
33 "name" => "location",
34 "type" => "geo",
35 "precision" => 4
36 ],
37 ])
38 ->simplePhrase(function(){
39 return $this
40 ->field('name')
41 ->directGenerator([
42 [
43 'field' => 'name',
44 'suggest_mode' => 'always'
45 ],
46 [
47 "field" => "title.reverse",
48 "suggest_mode" => "always",
49 "pre_filter" => "reverse",
50 "post_filter" => "reverse"
51 ]
52 ])
53 ->highlight([
54 'pre_tag' => "<em>",
55 'post_tag' => "</em>"
56 ])
57 ->collate([
58 'source' => [
59 'match' => [
60 "{{field_name}}" => "{{suggestion}}"
61 ]
62 ]
63 ])
64 ->smoothing([
65 'laplace' => [
66 'alpha' => 0.7
67 ]
68 ])
69 ->size(2)
70 ->getMap();
71 })
72 ->getMap();