其他分享
首页 > 其他分享> > ElasticSearch的基操和进阶查询

ElasticSearch的基操和进阶查询

作者:互联网

一,ElactisSearch简介

1. 定义

ElasticSearch是一个基于Lucene的搜索服务器。它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口。Elasticsearch是用Java开发的,并作为Apache许可条款下的开放源码发布,是当前流行的企业级搜索引擎。设计用于云计算中,能够达到实时搜索,稳定,可靠,快速,安装使用方便。

ES 是基于Lucene这个非常成熟的索引方案,另加上一些分布式的实现:集群,分片,复制等。

2. 优点

  1. 具备横向可扩展性:只需要增加一台服务器,做些配置,启动 ES 进程就可以快速并入集群。'
  2. 分片机制:同一个索引分成多个分片(sharding),类似于 redis 中的分片,采取分而治之的思想来更好地解决问题。
  3. 高可用:提供复制机制,一个分片可以设置多个复制,使得某台服务器宕机的话,集群依旧可以正常运行,并会把丢失的复制恢复到其它可用节点上'

3. 缺点

  1. 节点数据的一致性问题:其默认的机制是通过多播机制,同步元数据信息,但是在比较繁忙的集群中,可能会由于网络的阻塞,或者节点处理能力达到饱和导致各节点元数据不一致——也就是所谓的脑裂问题,这样会使集群处于不一致状态。目前并没有一个彻底的解决方案来解决这个问题,但是可以通过将工作节点与元数据节点分开的部署方案来缓解这种情况。
  2. 没有细粒度的权限管理,没有像MySQL那样的分各种用户,每个用户又有不同的权限。

4. 解决的问题

二,实现es操作的基本环境准备

1,下载ES的安装包解压后进入bin目录下,双击执行elasticsearch.bat(前提:自备Javajdk,因为ElasticSearch是基于lucence开发的,运行需要java jdk支持。所以要先安装JAVA环境,最低1.8)

………………………………
[2022-03-18T15:51:45,927][INFO ][o.e.l.LicenseService     ] [DESKTOP-I2SMELA] license [40d2c00e-52ad-4124-9506-526b9a613d3c] mode [basic] - valid
[2022-03-18T15:51:45,928][INFO ][o.e.x.s.s.SecurityStatusChangeListener] [DESKTOP-I2SMELA] Active license is now [BASIC]; Security is disabled
[2022-03-18T15:51:45,936][INFO ][o.e.g.GatewayService     ] [DESKTOP-I2SMELA] recovered [3] indices into cluster_state
[2022-03-18T15:51:46,098][INFO ][o.w.a.d.Monitor          ] [DESKTOP-I2SMELA] try load config from D:\ElasticSearch\elasticsearch-7.6.1\config\analysis-ik\IKAnalyzer.cfg.xml
[2022-03-18T15:51:46,101][INFO ][o.w.a.d.Monitor          ] [DESKTOP-I2SMELA] try load config from D:\ElasticSearch\elasticsearch-7.6.1\plugins\ik\config\IKAnalyzer.cfg.xml
[2022-03-18T15:51:46,278][WARN ][o.w.a.d.Monitor          ] [DESKTOP-I2SMELA] [Ext Loading] file not found: D:\ElasticSearch\elasticsearch-7.6.1\plugins\ik\config\my_ik
[2022-03-18T15:51:46,673][INFO ][o.e.h.AbstractHttpServerTransport] [DESKTOP-I2SMELA] publish_address {127.0.0.1:9200}, bound_addresses {127.0.0.1:9200}, {[::1]:9200}
[2022-03-18T15:51:46,674][INFO ][o.e.n.Node               ] [DESKTOP-I2SMELA] started

运行到started,并在浏览器上测试端口号如下图:

证明成功!

2, 安装ElasticSearch可视化插件ElasticSearch-head

这儿进行下载,里面有详细的安装步骤(前提是准备node环境,安装node,因为他是个node项目),解压后将在对应文件命令行界面输入npm install-->npm run start运行得到得到连接成功的界面:

……………………
D:\ElasticSearch\elasticsearch-head-master>grunt server
Running "connect:server" (connect) task
Waiting forever...
Started connect web server on http://localhost:9100

在浏览器下测试发现存在跨域问题。

3,解决跨域问题,因为在可视化插件上显示ES的信息需要连接ES的端口地址涉及到跨域问题,所以我们在ES的配置文件上修改一下配置去解决跨域:

        更改config文件下的 elasticsearch.yaml的配置:

http.cors.enabled: true 
http.cors.allow-origin: "*"
@注意,设置参数的时候:后面要有空格!

重启ES服务器,然后再连接得到下图:

并且能查看ES的一些基本信息

4.Kibana的安装 

Kibana是一个针对ElasticSearch的开源分析及可视化平台,用来搜索、查看交互存储在Elasticsearch索引中的数据。使用Kibana,可以通过各种图表进行高级数据分析及展示。

Kibana让海量数据更容易理解。它操作简单,基于浏览器的用户界面可以快速创建仪表板(dashboard)实时显示Elasticsearch查询动态。

设置Kibana非常简单。无需编码或者额外的基础架构,几分钟内就可以完成Kibana安装并启动Elasticsearch索引监测

我们可以自行在ElasticSearch官网下载,开箱即用,双击kibana.bat后可以看到运行成功:

………………
  log   [07:53:14.405] [info][status][plugin:vega@7.6.1] Status changed from uninitialized to green - Ready
  log   [07:53:14.408] [info][status][plugin:tagcloud@7.6.1] Status changed from uninitialized to green - Ready
  log   [07:53:15.078] [warning][reporting] 正在为 xpack.reporting.encryptionKey 生成随机密钥。要防止待处理报告在重新启 动时失败,请在 kibana.yml 中设置 xpack.reporting.encryptionKey
  log   [07:53:15.089] [info][status][plugin:reporting@7.6.1] Status changed from uninitialized to green - Ready
  log   [07:53:15.134] [info][listening] Server running at http://localhost:5601
  log   [07:53:15.285] [info][server][Kibana][http] http server running at http://localhost:5601

在浏览器中运行结果:

如果初始界面是英文的,我们也可以进行汉化。更改config目录下的kibana.yaml配置,将默认的i18n更改为i18n.local: "zh_CN"即可。

 三,ES中的基本Rest命令说明

简单操作:

1,创建索引

PUT  /索引名/类型名(可不写,默认为_doc)/文档id

kibana控制台输入:

PUT /test2/_doc/1
{
  "name":"stephen curry",
  "age":23,
  "address":"加利福利亚旧金山",
  "email":"12334424342342@qq.com"
}

 ES界面即可看到完成的自动增加的索引,数据也完成了添加。

2,指定字段类型

#创建规则
PUT /test2/_doc/2
{
  "mappings": {
    "properties": {
      "name":{
        "type": "text"
      },
      "age":{
        "type":"long"
      },
      "birth":{
        "type": "date"
      }
    }
  }
}

 3,查看:

GET /test2/_doc/2

结果:

{
  "_index" : "test2",
  "_type" : "_doc",
  "_id" : "2",
  "_version" : 2,
  "_seq_no" : 2,
  "_primary_term" : 1,
  "found" : true,
  "_source" : {
    "mappings" : {
      "properties" : {
        "name" : {
          "type" : "text"
        },
        "age" : {
          "type" : "long"
        },
        "birth" : {
          "type" : "date"
        }
      }
    }
  }
}

4,修改

(1)使用PUT在原有情况下进行覆盖

PUT /test2/_doc/1
{
  "name":"stephen james",
  "age":23,
  "address":"加利福利亚旧金山"
}

不过这种方法有时候会因为少些漏掉数据,不推荐

{
"_index": "test2",
"_type": "_doc",
"_id": "1",
"_version": 2,
"_score": 1,
"_source": {
"name": "stephen james",
"age": 23,
"address": "加利福利亚旧金山"
}
}

(2)使用POST的Rest命令进行修改

POST /test2/_doc/1/_update
{
  "doc":{
  "name":"湖人又被别人吊着锤了"
}}

可以看到修改成功:

{
"_index": "test2",
"_type": "_doc",
"_id": "1",
"_version": 3,
"_score": 1,
"_source": {
"name": "湖人又被别人吊着锤了",
"age": 23,
"address": "加利福利亚旧金山"
}
}

并且随着每次修改version都会依次增加,而且result会显示修改结果:

#! Deprecation: [types removal] Specifying types in document update requests is deprecated, use the endpoint /{index}/_update/{id} instead.
{
  "_index" : "test2",
  "_type" : "_doc",
  "_id" : "1",
  "_version" : 3,
  "result" : "updated",
  "_shards" : {
    "total" : 2,
    "successful" : 1,
    "failed" : 0
  },
  "_seq_no" : 4,
  "_primary_term" : 1
}

5,删除索引

通过DELETE命令来实现删除,根据请求来判断是删除索引还是文档记录

6,查询

简单的条件查询GET 索引/选填/选填id/_search?条件

#插入
PUT /test1/nba/1
{
   "name":"NBA",
   "age":150,
   "desc":"季后赛名额",
   "teams":["公牛", "热火","篮网","太阳","勇士"]
}

#查询
GET /test1/nba/_search?q=name:NBA

#结果
{
  "took" : 0,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 1,
      "relation" : "eq"
    },
    "max_score" : 0.2876821,
    "hits" : [
      {
        "_index" : "test1",
        "_type" : "nba",
        "_id" : "1",
        "_score" : 0.2876821,
        "_source" : {
          "name" : "NBA",
          "age" : 150,
          "desc" : "季后赛名额",
          "teams" : [
            "公牛",
            "热火",
            "篮网",
            "太阳",
            "勇士"
          ]
        }
      }
    ]
  }
}

复杂查询(排序,分页,高亮,模糊查询,精准查询)

插入数据

1,搜索过滤,只显示source需要的结果

#查询
GET test1/nba/_search
{
  "query":{
      "match": {
      "name":"NBA"
       }
},
"_source": ["name","teams"]
}

#结果
{
  "took" : 0,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 1,
      "relation" : "eq"
    },
    "max_score" : 0.9808291,
    "hits" : [
      {
        "_index" : "test1",
        "_type" : "nba",
        "_id" : "1",
        "_score" : 0.9808291,
        "_source" : {
          "teams" : [
            "公牛",
            "热火",
            "篮网",
            "太阳",
            "勇士"
          ],
          "name" : "NBA"
        }
      }
    ]
  }
}

2,排序

插入新的数据进行测试:

GET /test/user/_search
{
  "query": {
    "match": {
      "name": "张三"
    }
  },
  "_source": ["name","age"],
  "sort": [
    {
      "age": {
        "order": "asc"
      }
    }
  ]
}

3,分页

GET /test/user/_search
{
  "query": {
    "match": {
      "name": "张三"
    }
  },
  "_source": ["name","age"],
  "sort": [
    {
      "age": {
        "order": "asc"
      }
    }
  ],
  "from": 0,
  "size": 10
}

 

4,多条件查询--布尔值查询

4.1,must

GET /test/user/_search
{
  "query": {
    "bool": {
      "must": [
        {
        "match": {
          "name": "张三"}
        },
       {
         "match": {
          "age": 40}
        }
      ]
    }  
  }
}

 

4.2,should(or)

GET /test/user/_search
{
  "query": {
    "bool": {
      "should": [
        {
        "match": {
          "name": "李四"}
        },
       {
         "match": {
          "age": 40}
        }
      ]
    }
  }
}

 

 4.3,must_not(not)

GET /test/user/_search
{
  "query": {
    "bool": {
      "should": [
        {
        "match": {
          "name": "李四"}
        },
       {
         "match": {
          "age": 40}
        }
      ]
    }
  }
}

5,过滤器 filter 

GET /test/user/_search
{
  "query": {
    "bool": {
      "must": [
        {
        "match": {
          "name": "张三"
        }
        }
      ],
      "filter": {
#range 范围
        "range": {
          "age": {
#gte  大于等于
            "gte": 23 , 
            "lte": 40
          }
        }
      }
    }
    
  }
}

6,匹配多条件

GET /test/user/_search
{
  "query": {
  
  "match": {
    "tags": "旅游 阳光"
  }
    
  },
  "_source":  ["tags" ,"name"]
}

 

 7,多指匹配精确查询

GET test/_search
{
  "query": {
    "bool": {
      "should": [
        {
          "term": {
            "name.keyword": {
              "value": "张三"
            }
          }
        },{
          "term": {
            "age": {
              "value": 23
            }
          }
        }
      ]
    }
  }
}

8,搜索词高亮(自定义)

#插入数据1
PUT /test2/_doc/1/
{
   "name":"黎治跃",
   "age":20,
   "address":"湖北省武汉市",
   "email":"12334424342342@qq.com",
   "birth":"2000-10-21",
   "skill":["吃饭","吃饭吗"]
}
#插入数据2
PUT /test2/_doc/2/
{
   "name":"黎明",
   "age":27,
   "address":"湖北省武汉市",
   "email":"12334424342342@qq.com",
   "birth":"2000-10-21",
   "skill":["不吃饭","吃饭吗"]
}
#结果
{
  "took" : 742,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 2,
      "relation" : "eq"
    },
    "max_score" : 0.9534807,
    "hits" : [
      {
        "_index" : "test2",
        "_type" : "_doc",
        "_id" : "2",
        "_score" : 0.9534807,
        "_source" : {
          "name" : "黎明",
          "age" : 27,
          "address" : "湖北省武汉市",
          "email" : "12334424342342@qq.com",
          "birth" : "2000-10-21",
          "skill" : [
            "不吃饭",
            "吃饭吗"
          ]
        },
        "highlight" : {
          "name" : [
            "<p class='key' style='color:red'>黎</p><p class='key' style='color:red'>明</p>"
          ]
        }
      },
      {
        "_index" : "test2",
        "_type" : "_doc",
        "_id" : "1",
        "_score" : 0.16853255,
        "_source" : {
          "name" : "黎治跃",
          "age" : 20,
          "address" : "湖北省武汉市",
          "email" : "12334424342342@qq.com",
          "birth" : "2000-10-21",
          "skill" : [
            "吃饭",
            "吃饭吗"
          ]
        },
        "highlight" : {
          "name" : [
            "<p class='key' style='color:red'>黎</p>治跃"
          ]
        }
      }
    ]
  }
}

 结语:以上学习资源仅供个人笔记之用,总结的还是比较肤浅,主要视频学习可参考狂神说

标签:基操,test2,进阶,GET,doc,age,ElasticSearch,type,name
来源: https://blog.csdn.net/qq_42263280/article/details/123582949