• Elasticsearch


    1、搜索

    概念:用户输入想要的关键词,返回含有该关键词的所有信息。
    场景:
    1 互联网搜索:谷歌、百度、各种新闻首页
    2 站内搜索(垂直搜索):企业 OA 查询订单、人员、部门,电商网站内部搜索商品(淘宝、京东)场景。

    2、ElasticSearch与Solr比较

    1 总结
    2 1 es 基本是开箱即用 ( 解压就可以用 !) 【南京】 , 非常简单。 Solr
    安装略微复杂一丢丢 !
    3 2 Solr 利用 Zookeeper 进行分布式管理 ,
    Elasticsearch 自身带有分布式协调管理功能
    4 3 Solr 支持更多格式的数据 , 比如 JSON XML CSV ,
    Elasticsearch 仅支持 json 文件格式。
    5 4 Solr 官方提供的功能更多 , Elasticsearch 本身更注重于核心
    功能,高级功能多有第三方插件提供,例如图形化界面需要 kibana
    好支撑
    6 5.Solr 查询快 , 但更新索引时慢 ( 即插入删除慢 ) ,用于电商等查询
    多的应用 ;
    7
    8 ES 建立索引快 ( 即查询慢 ) ,即实时性查询快,用于 facebook 新浪等
    搜索。
    9 Solr 是传统搜索应用的有力解决方案,但 Elasticsearch 更适用于
    新兴的实时搜索应用。
    10 6 Solr 比较成熟,有一个更大,更成熟的用户、开发和贡献者社区,
    Elasticsearch 相对开发维护者较少 , 更新太快 , 学习使用成本较
    高。

    3、Elasticsearch 

    The Elastic Stack, 包括 Elasticsearch 【搜索,分析】、 Kibana 【可视 化】、 Beats Logstash 【数据的搜集】(也称为 ELK Stack )。能够安 全可靠地获取任何来源、任何格式的数据,然后实时地对数据进行搜索、 分析和可视化。
    Elaticsearch ,简称为 ES ES 是一个 开源的高扩展的分布式全文搜索引 , 是整个 ElasticStack 技术栈的核心。
    它可以近乎实时的存储、检索数据;本身扩展性很好,可以扩展到上百台
    服务器,处理 PB 级别的数据。

    4、ES的安装  

    1 、安装 JDK ,至少 1.8.0_73 以上版本,验证:
    java -version
    2 、下载和解压缩 Elasticsearch 安装包,查看目
    录结构。
    https://www.elastic.co/cn/downloads/elasticsearch
    下载地址: https://www.elastic.co/cn/downloads/
    历史版本下载: https://www.elastic.co/cn/downloads/past-releases/
    解压后,进入 bin 文件目录,点击 elasticsearch.bat 文件启动 ES 服务 。
    注意: 9300 端口为 Elasticsearch 集群间组件的通信端口, 9200 端口为
    浏览器访问的 http 协议 RESTful 端口。
    打开浏览器,输入地址: http://localhost:9200 ,测试返回结果,返回结
    果如下

    5、 Windows安装Kibana

    1 kibana es 数据的前端展现,数据分析时,可以方便地看到数据。作
    为开发人员,可以方便访问 es
    https://www.elastic.co/cn/downloads/
    历史版本下载: https://www.elastic.co/cn/downloads/past-releases/
    2 、下载,解压 kibana
    3 、启动 Kibana bin\kibana.bat
    4 、浏览器访问 http://localhost:5601 进入 Dev Tools 界面。像 plsql 一样支
    持代码提示。
    5 、发送 get 请求,查看集群状态 GET _cluster/health 。相当于浏览器访

    6、基本Rest命令说明

     

     7、Elasticsearch的相关命令

            7.1 创建索引

         

    PUT /索引名称/类型名称/1
    {
       数据
    }
    创建索引并往索引中添加一条文档

    (1)

    PUT / test1 / type1 / 1
    {
    "name" : "张三 " ,
    "age" : 18
    }

    (2)创建索引---但是不添加数据。
    PUT /索引名/类型
    PUT /qy150
    {
       "mappings":{
          "properties": {
              "name":{
                 "type": "text"
              },
              "age":{
                 "type": "integer"
              }
          }
       }
    }

    7.2、删除索引或数据

    DELETE /索引名                            删除索引

    DELETE /索引名/文档名/文档id     删除某一项

    7.3、查询有哪些索引

    GET  /_cat/indices?v

    7.4、 查询索引的结构

    GET /索引名

     7.5、添加文档

    # 必须指定id的值
    PUT /qy151/student/2
    {
       "name":"李四",
       "age":25
    }

    # 不指定id
    POST /qy151/student/
    {
       "name":"王五",
       "age": 32
    }

      // 如果没有将文档中的所有字段都写,修改后,没写的字段就会丢失
    POST /qy151/student/
      {
      "name" : " 流柚 "
    }
    //解决办法
    POST /qy151/student/_update
    {
    "doc":{
    "name" : " 流柚 ",
    }

    7.6、查询文档---id查询

    GET /索引名称/类型名称/id值

     

    7.7 查询所有文档

    GET /user/_doc/_search       其中的_doc 可以省略不写

    7.8 根据条件简单搜索

    GET /user/_doc/_search?q=name:流

    7.9 复杂查询

    7.9.1 查询匹配

    match :匹配(会使用分词器解析(先分析文档,然后进行查询))
    _source :过滤字段
    sort :排序
    form size 分页
    // 查询匹配
    GET /blog/user/_search
    {
    "query":{
    "match":{
    "name":" "
    }
    }
    ,
    "_source": ["name","desc"]         //限制只有name,desc这两个字段进行输出
    ,
    "sort": [                                         //sort 排序
    {
    "age": {
    "order": "asc"
    }
    }
    ]
    ,

     

    7.9.2 精确查询

    term 直接通过 倒排索引 指定 词条 查询
    适合查询 number date keyword ,不适合 text
    // 精确查询(必须全部都有,而且不可分,即按一个完整的词查询)
    // term 直接通过 倒排索引 指定的词条 进行精确查找的
    GET /blog/user/_search
    {
    "query":{
    "term":{
    "desc":" "
    }
    }
    }

     

     

    7.9.3  多条件查询(bool

    must 相当于 and
    should 相当于 or
    must_not 相当于 not (... and ...)
    filter 过滤

    (1)must

     (2)should

     (3)must_not

     7.10 高亮显示

    7.11 textkeyword

    text
    支持分词 全文检索 、支持模糊、精确查询 , 不支持聚合 , 排序操作 ;
    text 类型的最大支持的字符长度无限制 , 适合大字段存储;
    keyword
    不进行分词 直接索引 、支持模糊、支持精确匹配,支持聚合、排
    序操作。
    keyword 类型的最大支持的长度为 ——32766 UTF-8 类型的字符 ,
    可以通过设置 ignore_above 指定自持字符长度,超过给定长度后的
    数据将不被索引, 无法通过 term 精确匹配检索返回结果
    // 测试 keyword text 是否支持分词
    // 设置索引类型
    PUT /test
    {
    "mappings": {
    "properties": {
    "text":{
    "type":"text"
    },
    "keyword":{
    "type":"keyword"
    }
    }
    }
     
    }
    // 设置字段数据
    PUT /test/_doc/1
    {
    "text":" 测试 keyword text 是否支持分词 ",
    "keyword":" 测试 keyword text 是否支持分词 "
    }
    // text 支持分词
    // keyword 不支持分词
    GET /test/_doc/_search
    {
    "query":{
    "match":{
    "text":" 测试 "
    }
    }
    }// 查的到
    GET /test/_doc/_search
    {
    "query":{
    "match":{
    "keyword":" 测试 "
    }
    }
    }// 查不到,必须是 " 测试 keyword text 是否支持分词 " 才能查到
    GET _analyze
    {
    "analyzer": "keyword",
    "text": [" 测试 流"]
    }// 不会分词,即 测试流
    GET _analyze
    {
    "analyzer": "standard",
    "text": ["测试流"]
    }// 分为 测 试 流

     

     

     8、springboot整合Es

    (1)创建一个Springboot工程并加入相关的依赖

    创建springboot

     

     


           
                com.alibaba
                fastjson
                1.2.75
           

           
                org.springframework.boot
                spring-boot-starter-data-elasticsearch
           

           
                org.springframework.boot
                spring-boot-starter-web
           

           
                org.projectlombok
                lombok
                true
           

           
                org.springframework.boot
                spring-boot-starter-test
                test
           

       

     (2) 创建一个配置,获取ES工具类对象。
     

    1. @Configuration
    2. public class ESConfig {
    3. //该对象可以对我们的ES进行相关的操作
    4. @Bean
    5. public RestHighLevelClient restHighLevelClient(){
    6. RestHighLevelClient client = new RestHighLevelClient(
    7. RestClient.builder(new HttpHost("127.0.0.1",9200,"http")));
    8. return client;
    9. }
    10. }

    (3)对ES操作

    8.1 操作索引

    8.1.1 创建索引

    1. @Autowired
    2. private RestHighLevelClient client
    3. //PUT /索引名称
    4. @Test
    5. void testCreateIndex() throws Exception {
    6. //该类把创建索引的信息都封装到该类中
    7. CreateIndexRequest createIndexRequest=new CreateIndexRequest("qy151-index");
    8. CreateIndexResponse createIndexResponse = client.indices().create(createIndexRequest, RequestOptions.DEFAULT);
    9. System.out.println(createIndexResponse.isAcknowledged());
    10. }

    8.1.2  删除索引

    1. @Autowired
    2. private RestHighLevelClient client  
    3. @Test  
    4. public void testDeleteIndex() throws Exception {  
    5.   DeleteIndexRequest deleteIndexRequest=new DeleteIndexRequest("qy151-index");  
    6.     AcknowledgedResponse delete = client.indices().delete(deleteIndexRequest,
    7. RequestOptions.DEFAULT);  
    8.     System.out.println(delete.isAcknowledged());   }

     8.1.3 判断索引是否存在

    1. @Test
    2. public void testIndexExists() throws Exception{
    3. GetIndexRequest getIndexRequest=new GetIndexRequest("qy151-index");
    4. boolean exists = client.indices().exists(getIndexRequest, RequestOptions.DEFAULT);
    5. System.out.println(exists);
    6. }

    8.2 文档的操作

    8.2.1 添加文档

    1. //添加文档--PUT /索引/1 {name:"",age:"",address:""}
    2. @Test
    3. public void testInsertDoc() throws Exception{
    4. //ss-index为文档的名字
    5. IndexRequest indexRequest=new IndexRequest("ss-index");
    6. indexRequest.id("1");//指定文档的id
    7. //指定文档的内容:String文档的json内容,XContentType xContentType:以什么格式
    8. indexRequest.source(JSON.toJSONString(new User("张三","北京",22)), XContentType.JSON);
    9. IndexResponse indexResponse = client.index(indexRequest, RequestOptions.DEFAULT);
    10. System.out.println(indexResponse.getResult());
    11. }

    8.2.2 查询文档

    1. //获取文档 GET /索引/_doc/1
    2. @Test
    3. public void testGetDoc() throws Exception{
    4. GetRequest indexRequest=new GetRequest("ss-index");
    5. indexRequest.id("1");
    6. GetResponse getResponse = client.get(indexRequest, RequestOptions.DEFAULT);
    7. String string = getResponse.getSourceAsString();
    8. User user = JSON.parseObject(string, User.class);
    9. Map map = getResponse.getSourceAsMap();
    10. System.out.println(map.get("address"));
    11. }

    8.2.3 判断文档是否存在

    1. //判断索引文档是否存在
    2. @Test
    3. public void testDocExist() throws Exception{
    4. GetRequest indexRequest=new GetRequest("ss-index");
    5. indexRequest.id("2");
    6. boolean exists = client.exists(indexRequest, RequestOptions.DEFAULT);
    7. System.out.println(exists);
    8. }

    8.2.4 删除文档

    1. //文档操作---删除文档
    2. @Test
    3. public void testDeleteDoc() throws Exception{
    4. DeleteRequest deleteRequest=new DeleteRequest("ss-index");
    5. deleteRequest.id("1");
    6. DeleteResponse delete = client.delete(deleteRequest,RequestOptions.DEFAULT);
    7. System.out.println(delete.getResult());
    8. }

    8.2.5 修改文档

    1. @Test
    2. public void testUpdateDoc()throws Exception{
    3. UpdateRequest updateRequest=new UpdateRequest("qy151-index","1");
    4. User user = new User();
    5. user.setName("刘德华");
    6. updateRequest.doc(JSON.toJSONString(user), XContentType.JSON);
    7. UpdateResponse update = client.update(updateRequest, RequestOptions.DEFAULT);
    8. System.out.println(update.getResult());
    9. }

    8.2.6 批量添加文档

    1. //批量添加文档
    2. @Test
    3. public void testBuck() throws Exception{
    4. BulkRequest bulk=new BulkRequest("ss-index");
    5. List list=new ArrayList<>();
    6. list.add(new User("2","张三","北京",22));
    7. list.add(new User("3","张三他爸","上海",22));
    8. list.add(new User("4","李四","杭州",22));
    9. list.add(new User("5","李四他妈","广州",22));
    10. list.add(new User("6","王五","南京",22));
    11. //list.stream().forEach(item->bulk.add(new IndexRequest().id(item.getId()).source(JSON.toJSONString(item),XContentType.JSON)));
    12. for(User user:list){
    13. IndexRequest indexRequest=new IndexRequest();
    14. indexRequest.id(user.getId());
    15. indexRequest.source(JSON.toJSONString(user),XContentType.JSON);
    16. bulk.add(indexRequest);
    17. }
    18. BulkResponse bulkResponse = client.bulk(bulk,RequestOptions.DEFAULT);
    19. System.out.println(bulkResponse.hasFailures());
    20. }

    8.2.7 复杂查询

    1. //搜索查询---GET /索引/_search
    2. // {
    3. // "query":{
    4. // "":{}
    5. // },
    6. // "from":
    7. // "size":
    8. // "_source":["",""],
    9. // "sort":{}
    10. // }
    11. //1. 搜索请求对象SearchRequest
    12. //2. 构建一个条件对象SearchSourceBuilder
    13. //3. 把条件对象放入搜索请求对象中
    14. //4. 执行搜索功能
    15. @Test
    16. public void testSearch() throws Exception{
    17. //
    18. SearchRequest searchRequest=new SearchRequest("ss-index");
    19. //创建一个条件对象
    20. SearchSourceBuilder sourceBuilder=new SearchSourceBuilder();
    21. TermQueryBuilder matchQuery = QueryBuilders.termQuery("name", "张");
    22. sourceBuilder.query(matchQuery);
    23. //分页
    24. sourceBuilder.from(0);
    25. sourceBuilder.size(1);
    26. //排序
    27. // sourceBuilder.sort("age");
    28. //高亮
    29. HighlightBuilder highlightBuilder=new HighlightBuilder();
    30. highlightBuilder.field("name");
    31. highlightBuilder.preTags("");
    32. highlightBuilder.postTags("");
    33. sourceBuilder.highlighter(highlightBuilder);
    34. searchRequest.source(sourceBuilder);
    35. SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
    36. System.out.println("总条数:"+searchResponse.getHits().getTotalHits().value);
    37. SearchHit[] hits = searchResponse.getHits().getHits();
    38. Arrays.stream(hits).forEach(item-> System.out.println(item.getSourceAsString()));
    39. Arrays.stream(hits).forEach(item-> System.out.println(item.getHighlightFields()));
    40. }

  • 相关阅读:
    Python实现的吃东西小游戏
    单片机之从C语言基础到专家编程 - 4 C语言基础 - 4.11函数
    详细说说机器学习在交通领域的应用
    vue源码分析-响应式系统(二)
    CK草稿本
    redis 外部访问 --chatGPT
    Linux/Ubuntu环境搭建(二):创建添加新磁盘、搭建Samba服务器
    【逆向】Base64编码解码及逆向识别
    Qt编写物联网管理平台37-逻辑设计
    java接入烽火科技拾音器详细步骤
  • 原文地址:https://blog.csdn.net/younger123rtyui9/article/details/126349438