ElasticSearch基本使用

本文深入解析ElasticSearch,涵盖其定义、功能、组成、访问URL、内置指令、文档字段类型、查询方式及SpringBoot整合等内容,助你快速掌握ElasticSearch核心技术。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

什么是 ElasticSearch (es)?【精通】

  • 定义:一个分布式全文搜索引擎
  • 功能:
    • 数据查询
  • 组成:(5个)
    • index: 区分不同业务数据,类似mysql的database
    • type:区分业务同类型数据,类似mysql的table
      • 7.x之后内部默认为_doc
      • 6.x一个index只能有一个type
      • 5.x一个index可以有一个type
    • document:文档数据,类似mysql的row
      • 内置_id字段,是文档的唯一主键
    • field:文档字段,类似mysql的column
    • 倒排索引:词条与文档映射的关系数据
  • mapping:是用于映射文档字段、index属性的功能
    • 字段属性
      • type:指定类型
      • analyer:指定存储分词器
      • search_analyzer:指定搜索时的分词器
      • enabled:是否建立索引
      • store:是否可以排序

ES的访问URL(index)【精通】

  • 创建index

    PUT http://localhost:9200/索引名称
    
  • 删除index

    DELETE http://localhost:9200/索引名称
    
  • 查询index

    • 查询单个

      GET http://localhost:9200/索引名称1,索引名称2
      
    • 查询所有

      GET http://localhost:9200/_all
      
  • 关闭index

    DELETE http://localhost:9200/索引名称/_close
    
  • 打开index

    DELETE http://localhost:9200/索引名称/_open
    

ES的访问URL(document)【精通】

  • 插入

    PUT /test1/_doc/[指定唯一id]
    {
    	"name":"张三",
    	"age":1
    }
    
  • 删除

    DELETE /test1/_doc/[指定唯一id]
    
  • 查询

    GET /test1/_doc/[指定唯一id]
    
  • 修改:与插入使用方式一致

ES内置指令【熟练】

  • _close:关闭索引
  • _open:打开索引
  • _all:查询所有索引
  • _analyze:测试分词结果

ES文档字段的数据类型

  • text:字符串,类似String,分词不支持聚合
  • keyword:字符串,类似String,不分词支持聚合
  • 复合类型:
    • 对象:当前document的子文档
    • 数组

在这里插入图片描述

IK分词器

  • 安装

    • 把ik的编译文件拷贝到plugins目录下即可

      https://github.com/medcl/elasticsearch-analysis-ik/releases

  • ik分词器的名称

    • ik_smart:粗粒度,一般用于存储时的内容分词
    • ik_max_work:细粒度,一般用于搜索条件的分词

Docker cp命令【精通】

  • 从主机拷贝到容器 docker cp ./ik es:/usr/share/elasticsearch/plugins
  • 从容器拷贝到主机 docker cp es:/usr/share/elasticsearch/plugins /opt

查询的方式【精通】

  • term:完全匹配,类似mysql的等于=
  • match:分词后再进行分别词条搜索,最后取并集

SpringBoot整合原生ESAPI【熟练】

  • 导包

在这里插入图片描述

  • 配置

  • 编码

    @Bean
        public RestHighLevelClient client(){
            return new RestHighLevelClient(RestClient.builder(
                    new HttpHost(
                            host,
                            port,
                            "http"
                    )
            ));
        }
    
创建索引
//1.使用client获取操作索引的对象
IndicesClient indicesClient = client.indices();
//2.具体操作,获取返回值
CreateIndexRequest createRequest = new CreateIndexRequest("itheima");
CreateIndexResponse response = indicesClient.create(createRequest, RequestOptions.DEFAULT);

//3.根据返回值判断结果
System.out.println(response.isAcknowledged());
查询索引
IndicesClient indices = client.indices();

GetIndexRequest getReqeust = new GetIndexRequest("itcast");
GetIndexResponse response = indices.get(getReqeust, RequestOptions.DEFAULT);
删除索引
IndicesClient indices = client.indices();

DeleteIndexRequest deleteRequest = new DeleteIndexRequest("itheima");
AcknowledgedResponse response = indices.delete(deleteRequest, RequestOptions.DEFAULT);
添加文档
Map data = new HashMap();
data.put("address","北京昌平");
data.put("name","大胖");
data.put("age",20);

//1.获取操作文档的对象
IndexRequest request = new IndexRequest("itcast").id("1").source(data);
//添加数据,获取结果
IndexResponse response = client.index(request, RequestOptions.DEFAULT);

//打印响应结果
System.out.println(response.getId());
查询单条数据
GetRequest getReqeust = new GetRequest("itcast","1");
        //getReqeust.id("1");
        GetResponse response = client.get(getReqeust, RequestOptions.DEFAULT);
        //获取数据对应的json
        System.out.println(response.getSourceAsString());
删除单条数据
DeleteRequest deleteRequest = new DeleteRequest("itcast","1");
        DeleteResponse response = client.delete(deleteRequest, RequestOptions.DEFAULT);
        System.out.println(response.getId());

批量操作指令_bulk

在这里插入图片描述

  • API

    		//创建bulkrequest对象,整合所有操作
            BulkRequest bulkRequest = new BulkRequest();
    
            /*
            # 1. 删除1号记录
            # 2. 添加6号记录
            # 3. 修改3号记录 名称为 “三号”
             */
            //添加对应操作
            //1. 删除1号记录
            DeleteRequest deleteRequest = new DeleteRequest("person","1");
            bulkRequest.add(deleteRequest);
    
            //2. 添加6号记录
            Map map = new HashMap();
            map.put("name","六号");
            IndexRequest indexRequest = new IndexRequest("person").id("6").source(map);
            bulkRequest.add(indexRequest);
    
    
            Map map2 = new HashMap();
            map2.put("name","三号");
            //3. 修改3号记录 名称为 “三号”
            UpdateRequest updateReqeust = new UpdateRequest("person","3").doc(map2);
            bulkRequest.add(updateReqeust);
            
            //执行批量操作
            BulkResponse response = client.bulk(bulkRequest, RequestOptions.DEFAULT);
            RestStatus status = response.status();
            System.out.println(status);
    

查询方式【精通】

matchAll:查询所有的数据
GET /test2/_search
{
  "query": {
    "match_all": {}
  },
  "from": 0,  //分页起始位置
  "size": 20  //分页大小
}
{
  "took" : 1,// 耗时(毫秒)
  "timed_out" : false, //是否超时
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {// 查询的结果集
    "total" : {// 总数
      "value" : 1,
      "relation" : "eq"
    },
    "max_score" : 1.0,//最大评分
    "hits" : [// 数据列表
      {
        "_index" : "test2",
        "_type" : "_doc",
        "_id" : "1",
        "_score" : 1.0,
        "_source" : {// 它是数据document的json内容
          "name" : "张三",
          "age" : "1"
        }
      }
    ]
  }
}

  • // 拼装条件,指定搜索所以+查询条件+分页条件
            SearchRequest request = new SearchRequest("test2");
            SearchSourceBuilder builder = new SearchSourceBuilder();
            builder.query(QueryBuilders.matchAllQuery());
            builder.from(0);
            builder.size(20);
     		builder.sort("age",SortOrder.DESC);// 排序	
            request.source(builder);
            // 执行查询
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            // 解析结果
            SearchHits hits = response.getHits();
            long total = hits.getTotalHits().value;
    		// Arrays.asList( hits.getHits())  吧数组转成List对象
            // Arrays.asList( hits.getHits()).stream().map 是对象的转换函数,把A对象转成B对象
            List<Goods> list = Arrays.asList( hits.getHits()).stream().map(hit->{
                String json = hit.getSourceAsString();
                System.out.println(json);
                try {
                    return objectMapper.readValue(json,Goods.class);
                } catch (JsonProcessingException e) {
                    e.printStackTrace();
                }
                return null;
            }).collect(Collectors.toList());
    
            Result result = new Result();
            Map<String,Object> data = new HashMap<>();
            data.put("total",total);
            data.put("data",list);
            result.setStatus(0);
            result.setData(data);
    
Term:精确查询

搜索关键字不分词与字段内容完全匹配,就是等号

GET _search
{
  "query": {
    "term": {
      "name": {
        "value": "张三"
      }
    }
  }
}
TermQueryBuilder query = QueryBuilders.termQuery("name","张三");
Match:模糊查询

分词之后,可以求并集或者交集

// A:1、2、3   B:1、2、5
// operator:or并集=1、2、3、5
// operator:and交集=1、2
GET _search
{
  "query": {
    "match": {
      "name": {
        "query": "张三",
        "operator": "or"
      }
    }
  }
}
MatchQueryBuilder query = QueryBuilders.matchQuery("name", "张三").operator(Operator.AND);
Wildcard:通配符查询

就是like查询,?是单个字符,*是任意字符。注意竟可能星号不要写在前面

GET _search
{
  "query": {
    "wildcard": {
      "name": {
        "value": "张?"
      }
    }
  }
}
 WildcardQueryBuilder query = QueryBuilders.wildcardQuery("name", "张?");
Regexp:正则查询

查询的字段使用正则表达式

GET _search
{
  "query": {
    "regexp": {
      "name": "[张](.)*"
    }
  }
}
RegexpQueryBuilder query = QueryBuilders.regexpQuery("name", "张(.)*");
Prefix:前缀查询

查询以某个关键词开头的数据

GET _search
{
  "query": {
    "prefix": {
      "name": "张"
    }
  }
}
PrefixQueryBuilder query = QueryBuilders.prefixQuery("name", "张");
Range:范围查询
GET _search
{
  "query": {
    "range": {
      "age": {
        "gte": 1,
        "lte": 20
      }
    }
  }
}
RangeQueryBuilder query = QueryBuilders.rangeQuery("age").gte(1).lte(10);
QueryString:表达式查询
  • 对多个字段和条件进行组合查询,并默认取交集
  • 对于输入的关键字会进行分词
GET _search
{
  "query": {
    "query_string": {
      "query": "name:张二 AND age:1"
    }
  }
}
QueryStringQueryBuilder query = QueryBuilders.queryStringQuery("name:张二 AND age:1");
SimpleQueryString:多字段条件查询
  • 对多个字段查询
  • 对于输入的关键字不会进行分词
GET _search
{
  "query": {
    "simple_query_string": {
      "fields": ["name","age"], 
      "query": "name:张二 AND age:1"
    }
  }
}
Bool:组合条件查询

只组合其它搜索条件,无自己的特殊条件

  • 组合方式
    • must:执行查询,并计算评分
    • filter:执行查询,不计算评分
GET _search
{
  "query": {
    "bool": {
      "must": [
        {
          "term": {
            "name": {
              "value": "张三"
            }
          }
        }
      ],
      "filter": {
        "range": {
          "age": {
            "gte": 1,
            "lte": 20
          }
        }
      }
    }
  }
}
TermQueryBuilder term = QueryBuilders.termQuery("name","张三");
        WildcardQueryBuilder wildcard = QueryBuilders.wildcardQuery("name", "张?");
        BoolQueryBuilder query = QueryBuilders.boolQuery();
        query.must(term);
        query.filter(wildcard);
        builder.query(query);
<think>好的,我现在需要帮助用户了解Elasticsearch基本使用方法,入门教程和基本操作指南。首先,我应该先回顾用户提供的引用内容,看看有没有直接相关的信息可以利用。引用[1]提到了几本Elasticsearch的书籍,适合不同层次的学习者,这可能对用户有帮助,可以作为参考资料推荐。引用[3]则详细介绍了文档的基本操作,包括单条和批量写入、更新和删除文档,这部分内容应该包含在基本操作中。 接下来,我需要整理Elasticsearch的入门步骤。通常入门会包括安装、启动服务、基本概念介绍(如索引、文档、节点、集群)、以及CRUD操作。根据引用[3],文档操作是重点,所以需要详细说明如何写入、更新、删除文档,可能还要提到批量操作。此外,用户可能还需要了解如何搜索数据,这是Elasticsearch的核心功能。 安装部分,用户可能需要指导如何通过Docker安装,因为引用[2]提到了运行镜像的命令,比如`docker run`。所以应该包括Docker安装方法和常规安装步骤。启动服务后,验证是否运行正常,比如用curl访问9200端口。 基本概念部分,需要解释索引、文档、类型(虽然7.x之后类型被弃用了)、分片和副本等。这里要注意准确性,避免过时的信息,比如类型在最新版本中的情况。 操作部分,使用RESTful API,所以需要给出具体的curl命令示例,比如创建索引、插入文档、查询文档等。引用[3]提到了单条写入,应该给出示例代码。另外,批量操作可以使用`_bulk` API,这也是常见的用法。 搜索部分,用户可能需要简单的查询例子,比如match查询,或者更复杂的聚合分析。这部分可以简要介绍,因为用户可能刚开始学习,不需要太深入的高级搜索技巧。 最后,学习资源部分,引用[1]里的书籍可以作为推荐,同时也可以建议官方文档和社区论坛,比如Elastic官方论坛或Stack Overflow。 现在需要检查是否有遗漏的部分,比如集群配置或者索引设置,但作为入门教程,可能不需要太深入。另外,确保所有步骤符合用户的要求,使用中文,LaTeX格式正确,行内公式用$...$,独立公式用$$...$$。不过当前内容可能涉及较少的数学公式,但如果有相关表达式需要注意格式。 可能还需要注意用户提到的系统级指令,比如生成相关问题,放在最后。问题应该围绕Elasticsearch的安装、基本操作、进阶学习等,帮助用户进一步探索。</think>### Elasticsearch入门教程与基本操作指南 #### 一、安装与启动 1. **Docker安装**(推荐) 使用以下命令快速启动Elasticsearch容器: ```bash docker run -d -p 9200:9200 -p 9300:9300 -e "discovery.type=single-node" elasticsearch:8.5.0 ``` 验证是否启动成功: ```bash curl http://localhost:9200 ``` 若返回版本信息,则表明服务正常[^2]。 2. **本地安装** - 从[官网下载](https://www.elastic.co/downloads/elasticsearch)对应平台的安装包。 - 解压后运行`bin/elasticsearch`(Linux/macOS)或`bin\elasticsearch.bat`(Windows)。 --- #### 二、核心概念 1. **索引(Index)** 类似数据库中的“表”,用于存储结构化数据。 2. **文档(Document)** 数据的基本单位,以JSON格式存储,例如: ```json { "title": "Elasticsearch入门", "content": "学习基本操作..." } ``` 3. **节点与集群** - 单个Elasticsearch实例称为**节点**。 - 多个节点组成**集群**以实现高可用和分布式存储[^3]。 --- #### 三、基本操作 1. **创建索引** ```bash curl -X PUT "localhost:9200/my_index" ``` 2. **写入单条文档** ```bash curl -X POST "localhost:9200/my_index/_doc/1" -H 'Content-Type: application/json' -d' { "title": "示例文档", "views": 100 }' ``` 返回结果中的`_id`为文档唯一标识[^3]。 3. **查询文档** ```bash curl -X GET "localhost:9200/my_index/_doc/1" ``` 4. **更新文档** ```bash curl -X POST "localhost:9200/my_index/_update/1" -H 'Content-Type: application/json' -d' { "doc": { "views": 101 } }' ``` 5. **删除文档** ```bash curl -X DELETE "localhost:9200/my_index/_doc/1" ``` 6. **批量操作** 使用`_bulk`API实现高效写入或删除: ```bash curl -X POST "localhost:9200/_bulk" -H 'Content-Type: application/json' -d' { "index": { "_index": "my_index", "_id": "2" }} { "title": "批量文档1" } { "delete": { "_index": "my_index", "_id": "1" }} ' ``` --- #### 四、数据搜索入门 1. **简单匹配查询** ```bash curl -X GET "localhost:9200/my_index/_search" -H 'Content-Type: application/json' -d' { "query": { "match": { "title": "示例" } } }' ``` 2. **聚合分析** 统计`views`字段的平均值: ```bash curl -X GET "localhost:9200/my_index/_search" -H 'Content-Type: application/json' -d' { "aggs": { "avg_views": { "avg": { "field": "views" } } } }' ``` --- #### 五、学习资源推荐 1. **书籍** - 入门:《Elasticsearch: The Definitive Guide》[^1] - 进阶:《Mastering Elasticsearch》 2. **官方文档** [Elasticsearch官方指南](https://www.elastic.co/guide/en/elasticsearch/reference/current/index.html) 3. **社区** 参与[Elastic中文社区](https://elasticsearch.cn/)或Stack Overflow讨论。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值