一、索引库操作
索引库就类似数据库表,mapping映射就类似表的结构。我们要向es中存储数据,必须先创建“库”和“表”。
1.mapping映射属性
mapping是对索引库中文档的约束,常见的mapping属性包括:
-
type:字段数据类型,常见的简单类型有:-
字符串:text(可分词的文本)、keyword(精确值,例如:品牌、国家、ip地址)
-
数值:long、integer、short、byte、double、float、
-
布尔:boolean
-
日期:date
-
对象:object
-
-
index:是否创建倒排索引(字段能否被搜索),默认为true -
analyzer:使用哪种分词器,一般只有text类型需要使用 -
properties:指定字段的子字段
例如下面的json文档:
{
"age": 21,
"weight": 52.1,
"isMarried": false,
"info": "观止BlogNote",
"email": "zx@guanzhi.cn",
"score": [99.1, 99.5, 98.9],
"name": {
"firstName": "观",
"lastName": "止"
}
}
对应的每个字段索引库映射(mapping)如下:
-
age:类型为 integer;参与搜索,index应为true (创建倒排索引);无需分词器 (非text类字符串不需要用分词器)
-
weight:类型为float;参与搜索,index应为true;无需分词器
-
isMarried:类型为boolean;参与搜索,index应为true;无需分词器
-
info:类型为字符串,需要分词,因此是text;参与搜索,index应为true;分词器可以用ik_smart
-
email:类型为字符串,但是不需要分词,因此是keyword;不参与搜索,index应为false;无需分词器
-
score:es中无数组类型,但允许一个字段有多个值,因此我们只看其中元素的类型,类型为float;参与搜索,index应为true;无需分词器
-
name:类型为object,需要定义多个子属性
-
name.firstName;类型为字符串,但是不需要分词,因此是keyword;参与搜索,index应为true;无需分词器
-
name.lastName;类型为字符串,但是不需要分词,因此是keyword;参与搜索,index应为true;无需分词器
-
2.索引库的CRUD
这里我们先统一使用Kibana编写DSL的方式来演示,随后使用RestApi在Java中操作演示。
(1)创建索引库
- 请求方式:PUT
- 请求路径:/索引库名,可以自定义
- 请求参数:mapping映射
格式:
PUT /索引库名称
{
"mappings": {
"properties": {
"字段名":{
"type": "数据类型",
"analyzer": "分词器"
},
"字段名2":{
"type": "数据类型",
"index": boolean值
},
"字段名3":{
"properties": {
"子字段": {
"type": "数据类型"
}
}
},
// ...略
}
}
}
PUT /ssm
{
"mappings": {
"properties": {
"info": {
"type": "text",
"analyzer": "ik_smart"
},
"email": {
"type": "keyword",
"index": false
},
"name": {
"type": "object",
"properties": {
"firstName": {
"type": "keyword"
},
"lastName":{
"type": "keyword"
}
}
}
// ...略
}
}
}
(2)查询索引库
- 请求方式:GET
- 请求路径:/索引库名
- 请求参数:无
格式: GET /索引库名
(3)修改索引库
倒排索引结构虽然不复杂,但是一旦数据结构改变(比如改变了分词器),就需要重新创建倒排索引。因此索引库一旦创建,无法修改mapping中已有的字段,但是却允许添加新的字段到mapping中,因为不会对倒排索引产生影响。
- 请求方式:PUT
- 请求路径:/索引库名/_mapping,可以自定义
- 请求参数:mapping映射
格式:
PUT /索引库名/_mapping
{
"properties": {
"新字段名":{
"type": "数据类型"
}
}
}
(4)删除索引库
- 请求方式:DELETE
- 请求路径:/索引库名
- 请求参数:无
格式:DELETE /索引库名
二、文档操作
文档类似数据库的表
1.新增文档
- 请求方式:POST
- 请求路径:/索引库名/_doc/文档id
- 请求参数:json文档
格式:
POST /索引库名/_doc/文档id
{
"字段1": "值1",
"字段2": "值2",
"字段3": {
"子属性1": "值3",
"子属性2": "值4"
},
// ...
}
POST /ssm/_doc/1
{
"info":"程序员学java",
"email":"3513582592@qq.com",
"name":{
"firstName":"石朔铭",
"lastName":"ssm"
}
}
2.查询文档
- 请求方式:GET
- 请求路径:/索引库名称/_doc/文档id
- 请求参数:无
语法:
GET /索引库名称/_doc/文档id
3.删除文档
- 请求方式:DELETE
- 请求路径:/索引库名/_doc/文档id
- 请求参数:无
语法:
DELETE /索引库名/_doc/文档id
4.修改文档
修改有两种方式:
- 全量修改:会删除旧文档,添加新文档
- 增量修改:指定修改文档中的部分字段
(1)全量修改
全量修改是覆盖原来的文档,其本质是:
- 根据指定的id删除文档
- 新增一个相同id的文档
注意:如果根据id删除时,id不存在,第二步的新增也会执行,也就从修改变成了新增操作了。
- 请求方式:PUT
- 请求路径:/索引库名/_doc/文档id
- 请求参数:json文档
语法:
PUT /索引库名/_doc/文档id
{
"字段1": "值1",
"字段2": "值2",
// ... 略
}
PUT /ssm/_doc/1
{
"info":"程序员学jvav",
"email":"3513582592@qq.com",
"name":{
"firstName":"石朔铭",
"lastName":"ssm"
}
}
(2)增量修改
增量修改是只修改指定id匹配的文档中的部分字段。
- 请求方式:POST
- 请求路径:/索引库名/_update/文档id
- 请求参数:json文档
语法:
POST /索引库名/_update/文档id
{
"doc": {
"字段名": "新的值",
}
}
POST /ssm/_update/1
{
"doc":{
"info":"学习jvav"
}
}
三、RestClient操作
1.环境搭建
(1)引入依赖
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
</dependency>
因为SpringBoot默认的ES版本是7.6.2,所以我们需要覆盖默认的ES版本:
<properties>
<java.version>1.8</java.version>
<elasticsearch.version>7.12.1</elasticsearch.version>
</properties>
(2)初始化RestClient
在es提供的API中,与es一切交互都封装在一个名为RestHighLevelClient的类中,必须先完成这个对象的初始化,建立与elasticsearch的连接。
1.初始化RestHighLevelClient:
RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(
HttpHost.create("http://192.168.150.101:9200")
));
- 为了单元测试方便,我们创建一个测试类HotelIndexTest,然后将初始化的代码编写在@BeforeEach方法中:
@SpringBootTest
public class HotelIndexTest {
private RestHighLevelClient client;
@BeforeEach //每个方法前执行初始化client
void setUp(){
this.client = new RestHighLevelClient(RestClient.builder(
HttpHost.create("http://120.55.95.185:9200")
));
}
//每个方法前关闭
@AfterEach
void tearDown() throws IOException {
this.client.close();
}
@Test
void test() {
System.out.println(client);
}
}
2.RestClient操作索引库
(1)创建索引库
创建索引库,最关键的是分析mapping映射,而mapping映射要考虑的信息包括:
- 字段名
- 字段数据类型
- 是否参与搜索
- 是否需要分词
- 如果分词,分词器是什么?
其中:
- 字段名、字段数据类型,可以参考数据表结构的名称和类型
- 是否参与搜索要分析业务来判断,例如图片地址,就无需参与搜索
- 是否分词呢要看内容,内容如果是一个整体就无需分词,反之则要分词
- 分词器,我们可以统一使用ik_max_word
根据数据库表结构可创建如下索引库结构:
PUT /hotel
{
"mappings": {
"properties": {
"id": {
"type": "keyword"
},
"name":{
"type": "text",
"analyzer": "ik_max_word",
"copy_to": "all"
},
"address":{
"type": "keyword",
"index": false
},
"price":{
"type": "integer"
},
"score":{
"type": "integer"
},
"brand":{
"type": "keyword",
"copy_to": "all"
},
"city":{
"type": "keyword",
"copy_to": "all"
},
"starName":{
"type": "keyword"
},
"business":{
"type": "keyword"
},
"location":{
"type": "geo_point"
},
"pic":{
"type": "keyword",
"index": false
},
"all":{
"type": "text",
"analyzer": "ik_max_word"
}
}
}
}
几个特殊字段说明:
- location:地理坐标,里面包含精度、纬度
- all:一个组合字段,其目的是将多字段的值 利用copy_to合并,提供给用户搜索 (可利用all单个字段实现多字段搜索)
地理坐标说明:
copy_to说明,让Es对单个字段进行搜索,提高搜索效率:
java操作
- 创建一个constants常量类,定义上述mapping映射的JSON字符串常量:
public class HotelConstants {
public static final String MAPPING_TEMPLATE = "{\n" +
" \"mappings\": {\n" +
" \"properties\": {\n" +
" \"id\": {\n" +
" \"type\": \"keyword\"\n" +
" },\n" +
" \"name\":{\n" +
" \"type\": \"text\",\n" +
" \"analyzer\": \"ik_max_word\",\n" +
" \"copy_to\": \"all\"\n" +
" },\n" +
" \"address\":{\n" +
" \"type\": \"keyword\",\n" +
" \"index\": false\n" +
" },\n" +
" \"price\":{\n" +
" \"type\": \"integer\"\n" +
" },\n" +
" \"score\":{\n" +
" \"type\": \"integer\"\n" +
" },\n" +
" \"brand\":{\n" +
" \"type\": \"keyword\",\n" +
" \"copy_to\": \"all\"\n" +
" },\n" +
" \"city\":{\n" +
" \"type\": \"keyword\",\n" +
" \"copy_to\": \"all\"\n" +
" },\n" +
" \"starName\":{\n" +
" \"type\": \"keyword\"\n" +
" },\n" +
" \"business\":{\n" +
" \"type\": \"keyword\"\n" +
" },\n" +
" \"location\":{\n" +
" \"type\": \"geo_point\"\n" +
" },\n" +
" \"pic\":{\n" +
" \"type\": \"keyword\",\n" +
" \"index\": false\n" +
" },\n" +
" \"all\":{\n" +
" \"type\": \"text\",\n" +
" \"analyzer\": \"ik_max_word\"\n" +
" }\n" +
" }\n" +
" }\n" +
"}";
}
- 在hotel-demo中的HotelIndexTest测试类中,编写单元测试,实现创建索引:
@Test
void CreateHotelIndex() throws IOException {
//1.创建Request对象,指定索引库名称
CreateIndexRequest request = new CreateIndexRequest("hotel");
//2.准备请求参数DSL语句
request.source(MAPPING_TEMPLATE, XContentType.JSON);
//3.发送请求,indices中封装了索引库CRUD的方法
client.indices().create(request, RequestOptions.DEFAULT);
}
3.测试
(2)删除索引库
删除索引库操作非常简单,与创建索引库之间代码的差异,注意体现在Request对象上。依然是三步走:
-
1.创建Request对象。这次是DeleteIndexRequest对象
-
2.发送请求。改用delete方法
@Test
void DeleteHotelIndex() throws IOException {
DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest("hotel");
client.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
}
(3)查询索引库(判断索引库是否存在)
判断索引库是否存在,本质就是查询,对应的DSL是:
GET /hotel
因此与删除的Java代码流程是类似的。依然是三步走:
-
- 创建Request对象。这次是GetIndexRequest对象
-
- 发送请求。改用exists方法
@Test
void GetHotelIndex() throws IOException {
GetIndexRequest getIndexRequest = new GetIndexRequest("hotel");
boolean exists = client.indices().exists(getIndexRequest, RequestOptions.DEFAULT);
System.out.println(exists ? "hotel索引库存在" : "hotel索引库不存在");
}
(4)修改索引库
索引库一旦创建无法修改,只能重新添加新字段,可按照追加字段的DSL语法在CreateIndexRequest中实现。
3.RestClient操作文档
注:首先在测试类中初始化RestClient对象
(3.1)新增文档
目的:将数据库的酒店数据查询出来,写入elasticsearch中。
数据库查询后的结果是一个Hotel类型的对象。结构如下:
@Data
@TableName("tb_hotel")
public class Hotel {
@TableId(type = IdType.INPUT)
private Long id;
private String name;
private String address;
private Integer price;
private Integer score;
private String brand;
private String city;
private String starName;
private String business;
private String longitude;
private String latitude;
private String pic;
}
与我们的索引库结构存在差异:
- longitude和latitude需要合并为location
因此,我们需要定义一个新的类型,与索引库结构吻合:
package cn.itcast.hotel.pojo;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
public class HotelDoc {
private Long id;
private String name;
private String address;
private Integer price;
private Integer score;
private String brand;
private String city;
private String starName;
private String business;
private String location;
private String pic;
public HotelDoc(Hotel hotel) {
this.id = hotel.getId();
this.name = hotel.getName();
this.address = hotel.getAddress();
this.price = hotel.getPrice();
this.score = hotel.getScore();
this.brand = hotel.getBrand();
this.city = hotel.getCity();
this.starName = hotel.getStarName();
this.business = hotel.getBusiness();
this.location = hotel.getLatitude() + ", " + hotel.getLongitude();
this.pic = hotel.getPic();
}
}
完整代码:
注意:
- hotel对象需要转为HotelDoc对象
- 指定索引库id时为String类型
- HotelDoc需要序列化为json格式
@Test
void testAddDocument() throws IOException {
//1.根据id查询hotel对象
Hotel hotel = hotelService.getById(36934);
//2.将hotel转化为HotelDoc
HotelDoc hotelDoc = new HotelDoc(hotel);
//1.准备Request对象,指定索引库名和id
IndexRequest indexRequest = new IndexRequest("hotel").id(hotelDoc.getId().toString());
//2.传递参数,将hotelDoc转为json类型的字符串
indexRequest.source(JSON.toJSONString(hotelDoc), XContentType.JSON);
//3.发送请求
client.index(indexRequest, RequestOptions.DEFAULT);
}
(3.2)查询文档
查询操作非常简单,不过查询的目的是得到封装实体类结果。因此难点是解析为HotelDoc。
可以看到,结果是一个JSON,其中文档放在一个_source属性中,因此解析就是拿到_source,反序列化为Java对象即可。
@Test
void testGetDocument() throws IOException {
// 1.准备Request 指定索引库和id
GetRequest getRequest = new GetRequest("hotel", "36934");
//2. 发送请求,得到响应
GetResponse response = client.get(getRequest, RequestOptions.DEFAULT);
//3.解析_Source字段,得到json数据
String json = response.getSourceAsString();
//4.解析json,转化为HotelDoc对象
HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
System.out.println(hotelDoc);
}
(3.3)删除文档
与查询类似,对象为DeleteRequest
@Test
void testDeleteDocument() throws IOException {
// 1.准备Request 指定索引库和id
DeleteRequest getRequest = new DeleteRequest("hotel", "36934");
//2. 发送请求
client.delete(getRequest, RequestOptions.DEFAULT);
}
(3.4)修改文档
1.全量修改
删除旧文档,添加新文档。要手动写删除、新增操作
2.局部更新
局部更新DSL语法为:
POST /索引库名/_update/文档id
{
"doc":
{
"字段名": "新的值",
}
}
java操作对象为UpdateRequest:
@Test
void testUpdateDocument() throws IOException {
// 1.准备Request 指定索引库和id
UpdateRequest request = new UpdateRequest("hotel", "36934");
//2.准备请求参数
request.doc("city", "武汉", "price", "666");
//3. 发送请求
client.update(request, RequestOptions.DEFAULT);
}
(3.5)批量操作文档
批量处理BulkRequest,其本质就是将多个普通的CRUD请求组合在一起发送。
其中提供了一个add方法,用来添加其他请求:
可以看到,能添加的请求包括:
- IndexRequest,也就是新增
- UpdateRequest,也就是修改
- DeleteRequest,也就是删除
因此Bulk中添加了多个IndexRequest,就是批量新增功能了。
目的: 从数据中查询酒店数据,利用BulkRequest批量导入到索引库中
@Test
void testBulkDocument() throws IOException {
//获取hotel集合
List<Hotel> list = hotelService.list();
//1.获取request对象
BulkRequest bulkRequest = new BulkRequest();
//2.循环插入数据线
for(Hotel hotel : list) {
//2.1.转换为HotelDoc对象
HotelDoc hotelDoc = new HotelDoc(hotel);
//2.2调用add方法,进行批量添加(指定索引库,id,json数据)
bulkRequest.add(new IndexRequest("hotel")
.id(hotelDoc.getId().toString())
.source(JSON.toJSONString(hotelDoc), XContentType.JSON));
}
//3.发送请求
client.bulk(bulkRequest, RequestOptions.DEFAULT);
}
批量查询的DSL语句:GET /索引库名称/_search