1. 项目部署
1.1 导入 jar 包 (pox.xml)
<!-- spring-web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 热部署 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<!-- lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
<!-- 日志 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</dependency>
<!-- gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
<!--lang-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.8.1</version>
</dependency>
<!-- Apache开源组织提供的用于操作Java Bean的工具包 -->
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.1</version>
</dependency>
<!-- ES高级Rest Client -->
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>6.4.3</version>
</dependency>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>6.4.3</version>
</dependency>
1.2 索引库及映射(pojo)
1.2.1 Java 类映射
package com.csdn.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Product {
private Long id; // 主键
private String title; // 标题
private String category; // 分类
private String brand; // 品牌
private Double price; // 价格
private String images; // 图⽚地址
}
1.2.2 创建 csdn 索引库并编写映射配置
使⽤Kibana控制台向集群中创建yx索引库并编写映射配置
PUT /csdn
{
"settings": {
"number_of_shards": 3,
"number_of_replicas": 1
},
"mappings": {
"product": {
"properties": {
"id": {
"type": "keyword"
},
"title": {
"type": "text",
"analyzer": "ik_max_word"
},
"category": {
"type": "keyword"
},
"brand": {
"type": "keyword"
},
"price": {
"type": "double"
},
"images": {
"type": "keyword",
"index": false
}
}
}
}
}
2. CRUD 操作
2.1 初始化客户端
package com.csdn.es;
import com.google.gson.Gson;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.junit.After;
import org.junit.Before;
import org.springframework.boot.test.context.SpringBootTest;
import java.io.IOException;
@SpringBootTest
public class ElasticsearchTests {
private RestHighLevelClient restHighLevelClient;
// JSON⼯具
private Gson gson = new Gson();
/** 初始化客户端 */
@Before
public void init() {
RestClientBuilder restClientBuilder = RestClient.builder(
new HttpHost("127.0.0.1", 9201, "http"),
new HttpHost("127.0.0.1", 9202, "http"),
new HttpHost("127.0.0.1", 9203, "http")
);
restHighLevelClient = new RestHighLevelClient(restClientBuilder);
}
/** 关闭客户端 */
@After
public void close() throws IOException {
// 关闭客户端
restHighLevelClient.close();
}
}
2.2 新增/修改 ⽂档
@Test
public void insert() throws IOException {
// 1. 准备数据,Product对象中。准备文档对象的数据
Product product = new Product();
product.setId(10086L);
product.setTitle("iqoo手机旗舰机");
product.setCategory("手机");
product.setBrand("vivo");
product.setPrice(2999.00);
product.setImages("http://www.hh.com/img/1.png");
// 2.Product转化为JSON字符串
String json = gson.toJson(product);
// 3.创建一个索引请求的对象:访问的是哪一个索引、哪一个type、指定文档的信息
IndexRequest request = new IndexRequest("csdn", "product", product.getId().toString());
// 绑定写入的数据
request.source(json, XContentType.JSON);
// 4. 发送请求
IndexResponse response = restHighLevelClient.index(request, RequestOptions.DEFAULT);
System.err.println(response);
}
2.3 删除文档
/** 删除⽂档 */
@Test
public void delete() throws IOException {
// 准备删除的请求,参数为id
DeleteRequest request = new DeleteRequest("csdn", "product", "1");
// 发起请求
DeleteResponse response = restHighLevelClient.delete(request,
RequestOptions.DEFAULT);
System.err.println(response);
}
2.4 查询所有match_all
@Test
public void select() throws IOException {
// 创建查询对象
SearchRequest request = new SearchRequest("csdn");
// 查询构建工具对象的创建
SearchSourceBuilder builder = new SearchSourceBuilder();
// 添加绑定查询的类型:match_all、math、bool、term、fuzzy、filter
builder.query(QueryBuilders.matchAllQuery());
// 根据该类型执行查询操作
request.source(builder);
// 执行查询操作
SearchResponse search = restHighLevelClient.search(request, RequestOptions.DEFAULT);
// 解析查询结果,并遍历
for (SearchHit hit : search.getHits().getHits()) {
Product product = gson.fromJson(hit.getSourceAsString(), Product.class);
System.out.println(product);
}
}
2.5 关键字搜索match
@Test
public void matchQuery() throws IOException {
// 创建搜索对象
SearchRequest request = new SearchRequest();
// 查询构建⼯具
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
// 添加查询条件,通过QueryBuilders获取各种查询
sourceBuilder.query(QueryBuilders.matchQuery("title", "⼿机"));
request.source(sourceBuilder);
// 搜索
SearchResponse response = restHighLevelClient.search(request,
RequestOptions.DEFAULT);
// 解析
SearchHits hits = response.getHits();
SearchHit[] searchHits = hits.getHits();
for (SearchHit hit : searchHits) {
// 取出source数据
String json = hit.getSourceAsString();
// 反序列化
Product product = gson.fromJson(json, Product.class);
System.err.println(product);
}
}
2.6 范围查询range
@Test
public void rangeQuery() throws IOException {
// 查询构建⼯具
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
// 添加查询条件,通过QueryBuilders获取各种查询
sourceBuilder.query(QueryBuilders.rangeQuery("price").gt(3000).lt(5000));
basicQuery(sourceBuilder);
}
// 提取重复代码
public void basicQuery(SearchSourceBuilder sourceBuilder) throws IOException {
// 创建搜索对象
SearchRequest request = new SearchRequest();
request.source(sourceBuilder);
// 搜索
SearchResponse response = restHighLevelClient.search(request,
RequestOptions.DEFAULT);
// 解析
SearchHits hits = response.getHits();
SearchHit[] searchHits = hits.getHits();
for (SearchHit hit : searchHits) {
// 取出source数据
String json = hit.getSourceAsString();
// 反序列化
Product product = gson.fromJson(json, Product.class);
System.err.println(product);
}
}
RangeQueryBuilder提供多种范围查询API,常⻅⽤的⻅下:
2.7 source过滤
@Test
public void sourceFilter() throws IOException {
// 查询构建⼯具
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
// 添加查询条件,通过QueryBuilders获取各种查询
sourceBuilder.query(QueryBuilders.matchAllQuery());
// 添加source过滤
sourceBuilder.fetchSource(new String[] {"id", "title", "price"}, null);
basicQuery(sourceBuilder);
}
2.8 排序
@Test
public void sort() throws IOException {
// 创建搜索对象
SearchRequest request = new SearchRequest();
// 查询构建⼯具
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
// 添加查询条件,通过QueryBuilders获取各种查询
sourceBuilder.query(QueryBuilders.matchAllQuery());
// 添加排序
sourceBuilder.sort("price", SortOrder.DESC);
basicQuery(sourceBuilder);
}
2.9 分⻚
@Test
public void paging() throws IOException {
// 创建搜索对象
SearchRequest request = new SearchRequest();
// 查询构建⼯具
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
// 添加查询条件,通过QueryBuilders获取各种查询
sourceBuilder.query(QueryBuilders.matchAllQuery());
// 分⻚查询
int page = 1;
int size = 3;
int from = (page - 1) * size;
// 配置分⻚
sourceBuilder.from(from);
sourceBuilder.size(size);
basicQuery(sourceBuilder);
}