#Elasticsearch在linux安装及使用

一.Linux安装Elasticsearch

1.环境

php 7.2

elasticsearch 6.2.4

elasticsearch-php 6

2.安装JDK

网上教程很多,也可以参考本人教程之前写的Linux安装JDK

3.安装Elasticsearch

 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
cd /data/LPAPP

wget https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-6.2.4.tar.gz

tar zxvf elasticsearch-6.2.4.tar.gz

useradd es

passwd es

chown es:eselasticsearch-6.2.4

cd elasticsearch-6.2.4

vim ./config/elasticsearch.yml

添加 network.host: 0.0.0.0

su es

./bin/elasticsearch  // 启动

报错需重新进入es用户

exit

su es

4.安装Elasticsearch遇到的问题

1).max virtual memory areas vm.max_map_count [65530] is too low, increase to at least

root用户下

vim /etc/sysctl.conf

vm.max_map_count = 655360

/sbin/sysctl -p

2).max number of threads [3818] for user [es] is too low, increase to at least [4096]

root用户下

vim etc/security/limits.conf

* soft nproc 4096

* hard nproc 4096

3).max file descriptors [4096] for elasticsearch process is too low, increase to at least [65536]

root用户下

vim /etc/security/limits.conf

* soft nofile 65536

* hard nofile 65536

4).system call filters failed to install; check the logs and fix your configuration or disable system call filters at your own risk

在elasticsearch.yml中配置bootstrap.system_call_filter为false

bootstrap.memory_lock: false

bootstrap.system_call_filter: false

5.访问API

 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
curl -X GET http://127.0.0.1:9200

或

http://192.168.20.131:9200

{

  "name" : "Hw6FKjp",

  "cluster_name" : "elasticsearch",

  "cluster_uuid" : "V4QjQP5JT16hjpkohQ1fpg",

  "version" : {

    "number" : "6.2.4",

    "build_hash" : "ccec39f",

    "build_date" : "2018-04-12T20:37:28.497551Z",

    "build_snapshot" : false,

    "lucene_version" : "7.2.1",

    "minimum_wire_compatibility_version" : "5.6.0",

    "minimum_index_compatibility_version" : "5.0.0"

  },

  "tagline" : "You Know, for Search"

}

6.可视化工具Dejavu安装

1
2
3
4
$ docker run -p 1358:1358 -d appbaseio/dejavu


open http://localhost:1358/

二.项目安装Elasticsearch-PHP

1.php项目安装扩展包

1
2
3
composer.json 文件中加入 "elasticsearch/elasticsearch": "~6.0"

composer update

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
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
<?php

 

 

namespace App\Http\Controllers\Test;

 

 

use App\Handler\Traits\RedisTrait\ConfigCollegeTrait;

use App\Http\Controllers\Controller;

use App\Models\Course\CourseImproveLinkModel;

use Elasticsearch\ClientBuilder;

use Illuminate\Http\Request;

 

/**

 * es搜索用例

 * Class ElasticSearchTestController

 * @package App\Http\Controllers\Test

 */

class ElasticSearchTestController extends Controller

{

    use ConfigCollegeTrait;

 

    protected $client;

 

    function __construct()

    {

        //从hash配置中创建客户端

        $params       = [

            'hosts'   => [

                '192.168.20.138:9200'//host

            ],

            'retries' => 2,//重连次数

            'handler' => ClientBuilder::singleHandler()//http handler模式

        ];

        this->client = ClientBuilder::fromConfig(params);

        //$this->client = ClientBuilder::create()->build();

    }

 

    /**

     * 入口程序

     * @param Request $request

     * @return \Illuminate\Http\JsonResponse

     */

    public function index(Request $request)

    {

        //请求类型:1索引一个文档,2删除一个文档,3获取一个文档,4搜索一个文档,5删除一个索引,6创建一个索引,7更新一个文档,8批量索引,9索引示例

        type = request->input('type', 0);

        //9索引示例:1批量创建索引,2获取文档,3搜索文档,4删除索引

        exampleType = request->input('example_type', 0);

        //搜索关键字

        keywords = request->input('keywords', '');

        //分页

        page     = request->input('page', 1);

        pageSize = request->input('page_size', 10);

 

        try {

            $response = [];

            switch ($type) {

                case 1:#1索引一个文档

                    response = this->addTextIndex();

                    break;

                case 2:#2删除一个文档

                    response = this->delTextIndex();

                    break;

                case 3:#3获取一个文档

                    response = this->getTextIndex();

                    break;

                case 4:#4搜索一个文档

                    response = this->searchText();

                    break;

                case 5:#5删除一个索引

                    response = this->delIndex();

                    break;

                case 6:#6创建一个索引

                    response = this->addIndex();

                    break;

                case 7:#7更新一个文档

                    response = this->updateTextIndex();

                    break;

                case 8:#8批量索引

                    response = this->bulkTextIndex();

                    break;

                case 9:#9索引示例

                    switch ($exampleType) {

                        case 1:#1批量创建索引

                            response = this->bulkTextIndexExample();

                            break;

                        case 2:#2获取文档

                            response = this->getTextIndexExample();

                            break;

                        case 3:#3搜索文档

                            response = this->searchTextExample(keywords, page, $pageSize);

                            break;

                        case 4:#4删除索引

                            response = this->delIndexExample();

                            break;

                    }

                    break;

                default:

                    break;

            }

 

            return responseSuccess(1000, $response);

        } catch (\Exception $e) {

            returnData['code'] = e->getCode();

            returnData['msg']  = json_decode(e->getMessage(), true);

 

            return responseSuccess(1000, $returnData);

        }

    }

 

    /**

     * 索引一个文档

     * @return array

     */

    public function addTextIndex()

    {

        $params = [

            'index' => 'my_index',

            'type'  => 'my_type',

            'id'    => 'my_id',

            'body'  => ['testField' => 'abc']

        ];

 

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

 

        return $response;

    }

 

    /**

     * 更新一个文档

     * @return array

     */

    public function updateTextIndex()

    {

        $params = [

            'index' => 'my_index',

            'type'  => 'my_type',

            'id'    => 'my_id',

            'body'  => [

                'doc' => [

                    'new_field' => 'abc'

                ]

            ]

        ];

 

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

 

        return $response;

    }

 

    /**

     * 删除一个文档

     * @return array

     */

    public function delTextIndex()

    {

        $params = [

            'index' => 'my_index',

            'type'  => 'my_type',

            'id'    => 'my_id'

        ];

 

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

 

        return $response;

    }

 

    /**

     * 获取一个文档

     * @return array

     */

    public function getTextIndex()

    {

        $params = [

            'index' => 'my_index',

            'type'  => 'my_type',

            'id'    => 'my_id'

        ];

 

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

 

        return $response;

    }

 

    /**

     * 搜索一个文档

     * @return array

     */

    public function searchText()

    {

        $params = [

            'index' => 'my_index',

            'type'  => 'my_type',

            'body'  => [

                'query' => [

                    'match' => [

                        'testField' => 'abc'

                    ]

                ]

            ]

        ];

 

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

 

        return $response;

    }

 

    /**

     * 删除一个索引

     * @return array

     */

    public function delIndex()

    {

        $params = [

            'index' => 'my_index'

        ];

 

        response = this->client->indices()->delete($params);

 

        return $response;

    }

 

    /**

     * 创建一个索引

     * @return array

     */

    public function addIndex()

    {

        $params   = [

            'index' => 'my_index',

            'body'  => [

                'settings' => [

                    'number_of_shards'   => 2,

                    'number_of_replicas' => 0

                ]

            ]

        ];

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

 

        return $response;

    }

 

    /**

     * 批量索引

     * @return array

     */

    public function bulkTextIndex()

    {

        for (i = 0; i < 100; $i++) {

            $params'body' = [

                'index' => [

                    '_index' => 'my_index',

                    '_type'  => 'my_type',

                ]

            ];

 

            $params'body' = [

                'my_field'     => 'my_value',

                'second_field' => 'some more values'

            ];

        }

 

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

 

        return $response;

    }

 

    /**

     * 删除一个索引,实际示例

     * @return array

     */

    public function delIndexExample()

    {

        $params = [

            'index' => 'news_index'

        ];

 

        response = this->client->indices()->delete($params);

 

        return $response;

    }

 

    /**

     * 批量索引,实际示例

     * @return array

     * @throws \Exception

     */

    public function bulkTextIndexExample()

    {

        //请求教育家内网接口

        jYJNewsList = this->getJYJNewsList();

 

        $params = [];

        foreach (jYJNewsList as key => $news) {

            $params'body' = [

                'index' => [

                    '_index' => 'news_index',

                    '_type'  => 'news_type',

                    'id'    => 'news_id' . ($key + 1),

                ]

            ];

 

            $params'body' = [

                'id'         => $key + 1,

                'news_id'    => $news['id'],

                'news_title' => $news['text'],

            ];

        }

 

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

 

        return $response;

    }

 

    /**

     * 获取教育家资讯文数据,调用内网教育家接口

     * @param array $ids

     * @return array

     * @throws \Exception

     */

    protected function getJYJNewsList()

    {

        //请求内网接口

        $qs           = [8, 9, 10, 11, 12, 13, 18, 19, 20, 21, 30, 31];

        educationUrl = this->getConfigCollegeInfo('education_url');

        $newsList     = [];

        foreach (qs as a) {

            url      = educationUrl . '/api/v2/news/source/news_csearch_yyf?q=' . $a;

            data     = http_get(url);

            data     = data ? json_decode($data, true) : [];

            newsList = array_merge(newsList, $data);

        }

 

        return $newsList;

    }

 

    /**

     * 获取一个文档,实际示例

     * @return array

     */

    public function getTextIndexExample()

    {

        $params = [

            'index' => 'news_index',

            'type'  => 'news_type',

            'id'    => 'news_id_100'

        ];

 

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

 

        return $response;

    }

 

    /**

     * 搜索一个文档,实际示例

     * @return array

     */

    public function searchTextExample(keywords = '', page = 1, $pageSize = 10)

    {

        //查询条件

        $query = [

            "match_all" => new \stdClass()

        ];

        if ($keywords) {

            $query = [

                'match' => [

                    'news_title' => $keywords

                ]

            ];

        }

 

        $params = [

            'index' => 'news_index',

            'type'  => 'news_type',

            'body'  => [

                'query' => $query,

                'from'  => (page - 1) * pageSize,  // 分页

                'size'  => $pageSize,  // 每页数量

                'sort'  => [  // 排序

                    'id' => 'asc'   //对age字段进行降序排序

                ]

            ]

        ];

 

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

 

        $list = [];

        foreach (response['hits']['hits'] as hit) {

            list[] = hit['_source'];

        }

 

        return [

            'total'      => (int)$response'hits',

            'page'       => (int)$page,

            'page_size'  => (int)$pageSize,

            'page_total' => ceil(response['hits']['total'] / pageSize),

            'list'       => $list

        ];

    }

}

3.保持 Elasticsearch数据最新

A、工具同步(https://my.oschina.net/u/4000872/blog/2252620

1). logstash-input-jdbc

logstash官方插件,集成在logstash中,下载logstash即可,通过配置文件实现mysql与elasticsearch数据同步

优点

能实现mysql数据全量和增量的数据同步,且能实现定时同步.

版本更新迭代快,相对稳定.

作为ES固有插件logstash一部分,易用

缺点

不能实现同步删除操作,MySQL数据删除后Elasticsearch中数据仍存在.

同步最短时间差为一分钟,一分钟数据同步一次,无法做到实时同步.

2). go-mysql-elasticsearch

go-mysql-elasticsearch 是国内作者开发的一款插件

优点

能实现mysql数据增加,删除,修改操作的实时数据同步

缺点

无法实现数据全量同步Elasticsearch

仍处理开发、相对不稳定阶段

3). elasticsearch-jdbc

目前最新的版本是2.3.4,支持的ElasticSearch的版本为2.3.4, 未实践

优点

能实现mysql数据全量和增量的数据同步.

缺点

目前最新的版本是2.3.4,支持的ElasticSearch的版本为2.3.4

不能实现同步删除操作,MySQL数据删除后Elasticsearch中数据仍存在

B、使用消息队列实现ES增量同步(https://www.jianshu.com/p/2c968d23ef85