ElasticSearch基本操作

x33g5p2x  于2022-04-11 转载在 ElasticSearch  
字(5.2k)|赞(0)|评价(0)|浏览(398)

1.ElasticSearch 简介

Elasticsearch 是一个分布式、高扩展、高实时的搜索与数据分析引擎。它能很方便的使大量数据具有搜索、分析和探索的能力。可以帮助我们从海量数据中快速找到需要的内容。充分利用Elasticsearch的水平伸缩性,能使数据在生产环境变得更有价值。Elasticsearch是一个基于Lucene的搜索服务器。它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口。Elasticsearch是用Java语言开发的。

概念对比

MySQLElasticsearch说明
TableIndex索引(index),就是文档的集合,类似数据库的表(table)
RowDocument文档(Document),就是一条条的数据,类似数据库中的行(Row),文档都是JSON格式
ColumnField字段(Field),就是JSON文档中的字段,类似数据库中的列(Column)
SchemaMapping映射(Mapping)是索引中文档的约束,例如字段类型约束。类似数据库的表结构
SQLDSLDSL是elasticsearch提供的JSON风格的请求语句,用来操作elasticsearch,实现CRUD

优点对比

  • Mysql:擅长事务类型操作,可以确保数据的安全和一致性
  • Elasticsearch:擅长海量数据的搜索、分析、计算

2.索引库操作

2.1.mapping 属性

mapping 是对索引库中文档的约束,常见的mapping属性包括

  • type:字段类型

  • 字符串:text(可分词的文本)、keyword(精确值,不可拆分的词)

  • 数值:long、integer、short、byte 、double、float

  • 布尔:boolean

  • 日期:date

  • 对象:object

  • index:是否创建倒排索引,默认为true

  • analyzer:使用哪种分词器,一般与text联合使用

  • properties:该字段的子字段

更多mapping属性可查阅Elastic官方文档

2.2.索引库CRUD

创建索引库

【语法】

PUT /索引库名
{
  "mappings": {
    "properties": {
      "字段名1":{
        "type": "text",
        "analyzer": "ik_smart"
      },
      "字段名2":{
        "type": "object", 
        "properties": {
          "子字段":{
            "type": "keyword"
          }
        }
      },
      //....
    }
  }
}

【案例】

查询索引库

【语法】

GET /索引库名

【案例】

GET /why

删除索引库

【语法】

DELETE /索引库名

【案例】

DELETE /why

修改索引库

索引库只能添加新的字段,索引库一旦创建就无法修改

【案例】

PUT /索引库名/_mapping
{
  properties: {
    "新的字段名": {
      "type": "integer"
    }
  }
}

【案例】

3.文档操作

3.1.新增文档

【语法】

POST /索引库名称/_doc/文档id
{
  "字段1": "值1",
  "字段2": "值2",
  "字段3": {
    "子属性1": "值3",
    "子属性2": "值4"
  },
  //...
}

【案例】

3.2查询文档

【语法】

GET /索引库/_doc/文档id

【案例】

GET /why/_doc/1

3.3删除文档

【语法】

DELETE /索引库/_doc/文档id

【案例】

DELETE /why/_doc/1

3.4修改文档

【全量修改语法】

PUT /索引库名/_doc/文档id
{
	"字段1": "值1",
	"字段1": "值1",
	//...
}

【增量修改语法】

POST /索引库名/_update/文档id
{
	"doc": {
		"字段名" :"新的值"
	}
}

【案例】

两种修改方式的区别

  • 全量修改:这种方式会删除旧的文档,如果id存在就修改文档,如果id不存在就新增文档
  • 增量修改:这种方式只修改某个字段,如果id存在就修改字段,如果id不存在报404

4.RestClient

官方文档地址

4.1准备工作

一、导入工程和数据库
本文素材来自黑马张老师的视频

二、引入依赖

<properties>
	<java.version>1.8</java.version>
	<!--覆盖默认的ES版本-->
	<elasticsearch.version>7.12.1</elasticsearch.version>
</properties>

<!--ElasticSearch依赖-->
<dependency>
	<groupId>org.elasticsearch.client</groupId>
	<artifactId>elasticsearch-rest-high-level-client</artifactId>
	<version>7.12.1</version>
	</dependency>
</dependencies>

三、初始化JavaRestClient

private RestHighLevelClient client;
@BeforeEach //初始化RestHighLevelClient
void init(){
	this.client = new RestHighLevelClient(RestClient.builder(
		HttpHost.create("http://192.168.140.130:9200")
	));
}
@AfterEach  //关闭资源
void close() throws IOException {
	this.client.close();
}

4.2.RestClient操作索引库

创建索引库

@Test //创建索引库
    void testCreateHotelIndex() throws IOException {
        //1.创建Request对象
        CreateIndexRequest request = new CreateIndexRequest("hotel");
        //2.请求参数 source:创建索引库的DSL语句,xContentType:数据类型
        request.source(MAPPINF_TEMPLATE,XContentType.JSON);
        //3.发送请求,创建索引库
        client.indices().create(request, RequestOptions.DEFAULT);
    }

判断索引库是否存在

@Test //判断索引库是否存在
    void testIsExistHotelIndex() throws IOException {
        //1.创建Request对象 参数是要删除索引库的名称
        GetIndexRequest request = new GetIndexRequest("hotel");
        //3.发送请求,判断索引库是否存在
        boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
        System.out.println("索引库是否存在:"+exists);
    }

删除索引库

@Test //删除索引库
    void testDeleteHotelIndex() throws IOException {
        //1.创建Request对象 参数是要删除索引库的名称
        DeleteIndexRequest request = new DeleteIndexRequest("hotel");
        //3.发送请求,删除索引库
        client.indices().delete(request, RequestOptions.DEFAULT);
    }

4.3.RestClient操作文档

添加文档

@Test //添加文档
    void testAddIndexDocument() throws IOException {
        //在数据库查找数据
        Hotel hotel = hotelService.getById(61083L);
        //转化为文档类型
        HotelDoc hotelDoc = new HotelDoc(hotel);
        //1.创建request对象
        IndexRequest request = new IndexRequest("hotel").id(hotel.getId().toString());
        //2.准备document文档 将对象序列化成json格式的字符串
        String source = JSON.toJSONString(hotelDoc);
        request.source(source,XContentType.JSON);
        //3.发送请求,添加文档
        client.index(request,RequestOptions.DEFAULT);
    }

查询文档

@Test //查找文档
    void testGetIndexDocument() throws IOException{
        GetRequest request = new GetRequest("hotel","61083");
        GetResponse documentFields = client.get(request, RequestOptions.DEFAULT);
        String json = documentFields.getSourceAsString();
        //将json格式的字符串反序列化成对象
        HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
        System.err.println(hotelDoc);
    }

更新文档

@Test  //这是局部更新文档,全量更新文档代码与添加文档相同
    void testUpdateIndexDocument() throws IOException{
        UpdateRequest request = new UpdateRequest("hotel","61083");
        request.doc(
                "price","999",
                "score","50"
        );
        client.update(request,RequestOptions.DEFAULT);
    }

删除文档

@Test  //删除文档
    void deleteIndexDocument() throws IOException{
        DeleteRequest request = new DeleteRequest("hotel","61083");
        client.delete(request,RequestOptions.DEFAULT);
    }

批量导入文档

@Test  //批量导入文档
    void testMultipleAddIndexDocument() throws IOException{
        //从数据库中批量查询数据
        List<Hotel> hotels = hotelService.list();
        BulkRequest request = new BulkRequest();
        for (Hotel hotel : hotels) {
            HotelDoc hotelDoc = new HotelDoc(hotel);
            request.add(new IndexRequest("hotel")
                    .id(hotelDoc.getId().toString())
                    .source(JSON.toJSONString(hotelDoc),XContentType.JSON));
        }
        client.bulk(request,RequestOptions.DEFAULT);
    }

相关文章