• ElasticSearch 本地快速搭建与使用


    文章目录

    ElasticSearch 简介

    ElasticSearch是一个高度可扩展的开源搜索引擎并使用REST API,所以您值得拥有。 在本教程中,将介绍开始使用ElasticSearch的一些主要概念。

    下载并运行ElasticSearch

    ElasticSearch可以从elasticsearch.org下载对应的文件格式,如ZIP和TAR.GZ。下载并提取一个运行它的软件包之后不会容易得多,需要提前安装Java运行时环境。
    下载链接 https://www.elastic.co/products/elasticsearch

    在Windows上运行ElasticSearch

    • 从命令窗口运行位于bin文件夹中的elasticsearch.bat。这将会启动ElasticSearch在控制台的前台运行,这意味着我们可在控制台中看到运行信息或一些错误信息,并可以使用CTRL + C停止或关闭它。
    • 在启动过程中,ElasticSearch的实例运行会占用大量的内存,所以在这一过程中,电脑会变得比较慢,需要耐心等待,启动加载完成后电脑就可以正常使用了
    • 当ElasticSearch的实例并运行,您可以使用http://localhost:9200检查是否运行成功

    安装ik中文分词器

    下载地址:https://github.com/medcl/elasticsearch-analysis-ik/releases

    • 选择和已经下载的elasticsearch版本兼容的ik。
    • 解压后复制elasticsearch/plugins目录下
    • 重新运行elasticsearch.bat

    ik测试使用

    可以使用谷歌的Postman工具测试

    创建一个索引:

    curl -XPUT http://localhost:9200/index
    
    • 1

    创建一个映射

    curl -XPOST http://localhost:9200/index/fulltext/_mapping -H 'Content-Type:application/json' -d'
    {
            "properties": {
                "content": {
                    "type": "text",
                    "analyzer": "ik_max_word",
                    "search_analyzer": "ik_max_word"
                }
            }
    
    }'
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    添加索引文档测试数据

    curl -XPOST http://localhost:9200/index/fulltext/1 -H 'Content-Type:application/json' -d'
    {"content":"美国留给伊拉克的是个烂摊子吗"}
    
    curl -XPOST http://localhost:9200/index/fulltext/2 -H 'Content-Type:application/json' -d'
    {"content":"公安部:各地校车将享最高路权"}
    
    curl -XPOST http://localhost:9200/index/fulltext/3 -H 'Content-Type:application/json' -d'
    {"content":"中韩渔警冲突调查:韩警平均每天扣1艘中国渔船"}
    
    curl -XPOST http://localhost:9200/index/fulltext/4 -H 'Content-Type:application/json' -d'
    {"content":"中国驻洛杉矶领事馆遭亚裔男子枪击 嫌犯已自首"}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    查询突出显示

    curl -XPOST http://localhost:9200/index/fulltext/_search  -H 'Content-Type:application/json' -d'
    {
        "query" : { "match" : { "content" : "中国" }},
        "highlight" : {
            "pre_tags" : ["", ""],
            "post_tags" : ["", ""],
            "fields" : {
                "content" : {}
            }
        }
    }
    
    返回结果
    
    {
        "took": 14,
        "timed_out": false,
        "_shards": {
            "total": 5,
            "successful": 5,
            "failed": 0
        },
        "hits": {
            "total": 2,
            "max_score": 2,
            "hits": [
                {
                    "_index": "index",
                    "_type": "fulltext",
                    "_id": "4",
                    "_score": 2,
                    "_source": {
                        "content": "中国驻洛杉矶领事馆遭亚裔男子枪击 嫌犯已自首"
                    },
                    "highlight": {
                        "content": [
                            "中国驻洛杉矶领事馆遭亚裔男子枪击 嫌犯已自首 "
                        ]
                    }
                },
                {
                    "_index": "index",
                    "_type": "fulltext",
                    "_id": "3",
                    "_score": 2,
                    "_source": {
                        "content": "中韩渔警冲突调查:韩警平均每天扣1艘中国渔船"
                    },
                    "highlight": {
                        "content": [
                            "均每天扣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
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57

    安装ElasticSearch的Head插件

    安装head需要安装node和grunt

    • 安装nodejs:https://nodejs.org/en/download
    • 安装grunt:npm install -g grunt-cli 安装完成后执行grunt -version查看是否安装成功,会显示安装的版本号

    修改elasticsearch.yml文件
    去掉network.host: 192.168.0.1的注释并改为network.host: 0.0.0.0,
    去掉cluster.namenode.name;http.port的注释

    在文件的末尾加入以下代码:

    http.cors.enabled: true 
    http.cors.allow-origin: "*"
    node.master: true
    node.data: true
    
    • 1
    • 2
    • 3
    • 4

    Linux安装ElasticSearch

    https://blog.csdn.net/weixin_41615494/article/details/79591335

    访问elasticSearch官网地址 https://www.elastic.co/
    下载指定版本的安装包:elasticsearch-6.1.1.tar.gz,上传至指定目录/usr/local/elasticsearch

    #解压
    tar -zxvf elasticsearch-6.1.1.tar.gz
    #创建数据存储目录
    mkdir -p /usr/local/elasticsearch/data
    #创建日志存储目录
    mkdir -p /usr/local/elasticsearch/logs
    
    #进入到es安装目录下的config文件夹中,修改elasticsearch.yml 文件
    
    #配置es的集群名称,默认是elasticsearch,es会自动发现在同一网段下的es,如果在同一网段下有多个集群,就可以用这个属性来区分不同的集群。
    cluster.name: qxw-application
    #节点名称
    node.name: node-1 
    #设置索引数据的存储路径
    path.data: /usr/local/elasticsearch/data 
    #设置日志的存储路径
    path.logs: /usr/local/elasticsearch/logs 
    #设置当前的ip地址,通过指定相同网段的其他节点会加入该集群中
    network.host: 192.168.1.191
    #设置对外服务的http端口
    http.port: 9200 
    #设置集群中master节点的初始列表,可以通过这些节点来自动发现新加入集群的节点
    discovery.zen.ping.unicast.hosts: ["node-1"]
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    修改host 文件,执行命令 vi /etc/hosts

    因为安全问题elasticsearch 不让用root用户直接运行,所以要创建新用户。

    useradd es
    passwd es
    再输入两次密码(自定义)
    
    #给新创建用户文件夹执行权限
    chown -R es:es /usr/local/elasticsearch
    
    切换es用户:su es
    
    启动集群命令:
    cd  /usr/local/elasticsearch
    bin/elasticsearch
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    在es用户下启动时报错

    原因:Centos6不支持SecComp,而ES默认bootstrap.system_call_filter为true进行检测,所以导致检测失败,失败后直接导致ES不能启动
    
    详见 :https://github.com/elastic/elasticsearch/issues/22899
    解决方案:
    
    在elasticsearch.yml中新增配置bootstrap.system_call_filter,设为false。
    bootstrap.system_call_filter: false
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    第一个问题的原因:

    原因:无法创建本地文件问题,用户最大可创建文件数太小
    
    解决方案:切换到root用户,编辑limits.conf配置文件, 添加类似如下内容:
    
    vi /etc/security/limits.conf
    
    添加如下内容: 注意*不要去掉了
    
    * soft nofile 65536
    
    * hard nofile 131072
    
    备注:* 代表Linux所有用户名称(比如 hadoop)
    
    需要保存、退出、重新登录才可生效。
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    第二个错误的原因:

    原因:无法创建本地线程问题,用户最大可创建线程数太小
    
    解决方案:切换到root用户,进入limits.d目录下,修改90-nproc.conf 配置文件。
    
    vi /etc/security/limits.d/90-nproc.conf
    
    找到如下内容:
    
    * soft nproc 1024
    
    #修改为
    
    * soft nproc 4096
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    第三个错误的原因:

    原因:最大虚拟内存太小
    
    每次启动机器都手动执行下。
    
    root用户执行命令:
    
    执行命令:sysctl -w vm.max_map_count=262144
    
    查看修改结果命令:sysctl -a|grep vm.max_map_count  看是否已经修改
    
    永久性修改策略:
    
    echo "vm.max_map_count=262144" >> /etc/sysctl.conf
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    切换到es用户执行:bin/elasticsearch
    访问:http://192.168.1.191:9200/

    #后台启动
    [es@localhost elasticsearch-6.4.0]$ ./bin/elasticsearch -d
    [es@localhost elasticsearch-6.4.0]$ jps
    27587 Jps
    27573 Elasticsearch
    
    • 1
    • 2
    • 3
    • 4
    • 5

    java中使用elastaicsearch(RestHighLevelClient)

    官方文档可以得知,现在存在至少三种Java客户端。

    1. Transport Client
    2. Java High Level REST Client
    3. Java Low Level Rest Client
    4. 强烈建议ES5及其以后的版本使用Java High Level REST Client

    java High Level REST Client 介绍

    • Java High Level REST Client 是基于Java Low Level REST Client的,每个方法都可以是同步或者异步的。同步方法返回响应对象,而异步方法名以“async”结尾,并需要传入一个监听参数,来确保提醒是否有错误发生。
    • Java High Level REST Client需要Java1.8版本和ES。并且ES的版本要和客户端版本一致。和TransportClient接收的参数和返回值是一样的。

    引入maven依赖

    
                org.elasticsearch.client
                elasticsearch-rest-high-level-client
                6.2.3
            
    
    • 1
    • 2
    • 3
    • 4
    • 5

    Java基础操作

    public class RestClientTest {
    
        public static void main(String[] args) {
    //        index();
    //        bacthIndex();
             queryTest();
        }
        
        /**
         * 插入数据
         */
        public  static  void  index(){
            try {
                //RestHighLevelClient实例需要低级客户端构建器来构建
                RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
                IndexRequest indexRequest = new IndexRequest("demo", "demo");
                JSONObject obj=new JSONObject();
                obj.put("title","标题图表题大法师飞洒发顺丰三");
                obj.put("time","2018-08-21 17:43:50");
                indexRequest.source(obj.toJSONString(),XContentType.JSON);
                //添加索引
                client.index(indexRequest);
                client.close();
    
                //http://localhost:9200/demo/demo/_search  浏览器运行查询数据
            }catch (Exception e){
                    e.printStackTrace();
            }
        }
    
        /**
         * 批量插入数据
         */
       public static  void  bacthIndex(){
           RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
           List requests = new ArrayList<>();
           requests.add(generateNewsRequest("中印边防军于拉达克举行会晤 强调维护边境和平", "2018-01-27T08:34:00Z"));
           BulkRequest bulkRequest = new BulkRequest();
           for (IndexRequest indexRequest : requests) {
               bulkRequest.add(indexRequest);
           }
           try {
               client.bulk(bulkRequest);
               client.close();
           } catch (Exception e) {
               e.printStackTrace();
           }
       }
        public static IndexRequest generateNewsRequest(String title,String publishTime){
            IndexRequest indexRequest = new IndexRequest("demo", "demo");
            JSONObject obj=new JSONObject();
            obj.put("title",title);
            obj.put("time",publishTime);
            indexRequest.source(obj.toJSONString(),XContentType.JSON);
            return indexRequest;
        }
    
        /**
         * 查询操作
         * https://blog.csdn.net/paditang/article/details/78802799
         * https://blog.csdn.net/A_Story_Donkey/article/details/79667670
         * https://www.cnblogs.com/wenbronk/p/6432990.html
         */
        public static  void  queryTest(){
            RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
            // 这个sourcebuilder就类似于查询语句中最外层的部分。包括查询分页的起始,
            // 查询语句的核心,查询结果的排序,查询结果截取部分返回等一系列配置
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
            try {
                // 结果开始处
                sourceBuilder.from(0);
                // 查询结果终止处
                sourceBuilder.size(2);
                // 查询的等待时间
                sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
    
                /**
                 * 使用QueryBuilder
                 * termQuery("key", obj) 完全匹配
                 * termsQuery("key", obj1, obj2..)   一次匹配多个值
                 * matchQuery("key", Obj) 单个匹配, field不支持通配符, 前缀具高级特性
                 * multiMatchQuery("text", "field1", "field2"..);  匹配多个字段, field有通配符忒行
                 * matchAllQuery();         匹配所有文件
                 */
                MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("title", "费德勒");
    
                //分词精确查询
    //            TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("tag", "体育");
    
    
    //            // 查询在时间区间范围内的结果  范围查询
    //            RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("publishTime");
    //            rangeQueryBuilder.gte("2018-01-26T08:00:00Z");
    //            rangeQueryBuilder.lte("2018-01-26T20:00:00Z");
    
                // 等同于bool,将两个查询合并
                BoolQueryBuilder boolBuilder = QueryBuilders.boolQuery();
                boolBuilder.must(matchQueryBuilder);
    //            boolBuilder.must(termQueryBuilder);
    //            boolBuilder.must(rangeQueryBuilder);
                sourceBuilder.query(boolBuilder);
    
                // 排序
    //            FieldSortBuilder fsb = SortBuilders.fieldSort("date");
    //            fsb.order(SortOrder.DESC);
    //            sourceBuilder.sort(fsb);
    
    
                SearchRequest searchRequest = new SearchRequest("demo");
                searchRequest.types("demo");
                searchRequest.source(sourceBuilder);
                SearchResponse response = client.search(searchRequest);
                System.out.println(response);
                client.close();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
    
    • 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
  • 相关阅读:
    论文笔记:Skeleton Key: Image Captioning by Skeleton-Attribute Decomposition
    Web应用的工作原理
    未能将“obj\Debug\IOControl.exe”复制到“bin\Debug\IOControl.exe
    消息中间件Kafuka学习——初次配置使用
    计算机网络(二)
    [产品体验] GPT4识图功能
    Vue 优雅的减少请求次数
    小项目应该如何进行跨平台方案选型
    ESP8266-Arduino编程实例-SHT20温湿度传感器驱动
    在 TensorFlow 中调试
  • 原文地址:https://blog.csdn.net/m0_54849806/article/details/126359264