Elasticsearch从入门到精通-09JavaAPI操作ES
👏作者简介:大家好,我是程序员行走的鱼
📖 本篇主要介绍和大家一块学习一下如何集成java代码去实现索引的增删改查、文档的增删改查、以及在java代码中如何进行精确查询、模糊查询、分页查询、范围查询、聚合统一等。
一 Elasticsearch-javaAPI使用
maven依赖:
xml
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>7.8.0</version>
</dependency>
<!-- elasticsearch的客户端 -->
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.8.0</version>
</dependency>
<!-- elasticsearch依赖2.x的log4j -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.8.2</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.8.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.9</version>
</dependency>
<!-- junit单元测试 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>2.0.4</version>
</dependency>
</dependencies>
测试连接:
java
public class ESTest_Client {
public static void main(String[] args) throws IOException {
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("ip",9200,"http")));
esClient.close();
}
}
1.索引操作
创建索引
json
public class ESTest_Index_Create {
public static void main(String[] args) throws IOException {
//创建ES客户端
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("ip",9200,"http")));
// 创建索引
CreateIndexRequest request = new CreateIndexRequest("user");
CreateIndexResponse createIndexResponse =
esClient.indices().create(request, RequestOptions.DEFAULT);
// 响应状态
boolean acknowledged = createIndexResponse.isAcknowledged();
System.out.println("索引操作 :" + acknowledged);
//关闭客户端
esClient.close();
}
}
查看索引
java
public class ESTest_Index_Search {
public static void main(String[] args) throws IOException {
//创建ES客户端
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("ip",9200,"http")));
// 查询索引
GetIndexRequest request = new GetIndexRequest();
org.elasticsearch.client.indices.GetIndexRequest getIndexRequest = new org.elasticsearch.client.indices.GetIndexRequest("user");
GetIndexResponse getIndexResponse = esClient.indices().get(getIndexRequest, RequestOptions.DEFAULT);
// 响应状态
System.out.println(getIndexResponse.getAliases());
System.out.println(getIndexResponse.getMappings());
System.out.println(getIndexResponse.getSettings());
//关闭客户端
esClient.close();
}
}
删除索引
java
public class ESTest_Index_Delete {
public static void main(String[] args) throws IOException {
//创建ES客户端
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("ip",9200,"http")));
//删除索引请求对象
DeleteIndexRequest request = new DeleteIndexRequest("user");
// 发送请求,获取响应
AcknowledgedResponse response = esClient.indices().delete(request,
RequestOptions.DEFAULT);
// 操作结果
System.out.println("操作结果 : " + response.isAcknowledged());
//关闭客户端
esClient.close();
}
}
2.文档操作
插入单条文档
java
/**
* @Author wcy
* @Description //插入单条文档
* @Date 17:43 2022-12-01
* @Param
**/
public class ESTest_Doc_Insert {
public static void main(String[] args) throws IOException {
//创建ES客户端
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("ip",9200,"http")));
IndexRequest request = new IndexRequest();
request.index("user").id("1001");
User user = new User();
user.setName("zhangsan");
user.setAge(30);
user.setSex("男");
ObjectMapper objectMapper = new ObjectMapper();
String userJson = objectMapper.writeValueAsString(user);
request.source(userJson, XContentType.JSON);
IndexResponse response = esClient.index(request, RequestOptions.DEFAULT);
System.out.println("_index:" + response.getIndex());
System.out.println("_id:" + response.getId());
System.out.println("_result:" + response.getResult());
//关闭客户端
esClient.close();
}
}
根据id修改文档
java
/**
* @Author wcy
* @Description //修改文档
* @Date 17:53 2022-12-01
* @Param
**/
public class ESTest_Doc_Update {
public static void main(String[] args) throws IOException {
//创建ES客户端
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("ip",9200,"http")));
// 修改文档 - 请求对象
UpdateRequest request = new UpdateRequest();
// 配置修改参数
request.index("user").id("1001");
// 设置请求体,对数据进行修改
request.doc(XContentType.JSON, "sex", "女");
// 客户端发送请求,获取响应对象
UpdateResponse response = esClient.update(request, RequestOptions.DEFAULT);
System.out.println("_index:" + response.getIndex());
System.out.println("_id:" + response.getId());
System.out.println("_result:" + response.getResult());
//关闭客户端
esClient.close();
}
}
根据id查询文档
java
/**
* @Author wcy
* @Description //查询文档
* @Date 17:56 2022-12-01
* @Param
**/
public class ESTest_Doc_Get {
public static void main(String[] args) throws IOException {
//创建ES客户端
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("ip",9200,"http")));
//1.创建请求对象
GetRequest request = new GetRequest().index("user").id("1001");
//2.客户端发送请求,获取响应对象
GetResponse response = esClient.get(request, RequestOptions.DEFAULT);
3.打印结果信息
System.out.println("_index:" + response.getIndex());
System.out.println("_type:" + response.getType());
System.out.println("_id:" + response.getId());
System.out.println("source:" + response.getSourceAsString());
//关闭客户端
esClient.close();
}
}
根据id删除文档
java
public class ESTest_Doc_Delete {
public static void main(String[] args) throws IOException {
//创建ES客户端
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("ip",9200,"http")));
//创建请求对象
DeleteRequest request = new DeleteRequest().index("user").id("1001");
//客户端发送请求,获取响应对象
DeleteResponse response = esClient.delete(request, RequestOptions.DEFAULT);
//打印信息
System.out.println(response.toString());
//关闭客户端
esClient.close();
}
}
3.高级查询
查询所有文档
java
/**
* @Author wcy
* @Description //高级查询
* @Date 10:15 2022-12-02
* @Param
**/
public class ESTest_Doc_Query {
public static void main(String[] args) throws IOException {
//创建ES客户端
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("ip",9200,"http")));
//1.term查询
SearchRequest request = new SearchRequest();
request.indices("user");
request.source(new SearchSourceBuilder().query(QueryBuilders.termQuery("age", 40)));
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
System.out.println(hits.getTotalHits());
System.out.println(response.getTook());
for ( SearchHit hit : hits ) {
System.out.println(hit.getSourceAsString());
}
//关闭客户端
esClient.close();
}
}
条件查询
json
/**
* @Author wcy
* @Description //高级查询
* @Date 10:15 2022-12-02
* @Param
**/
public class ESTest_Doc_Query {
public static void main(String[] args) throws IOException {
//创建ES客户端
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("ip",9200,"http")));
//1.term查询
SearchRequest request = new SearchRequest();
request.indices("user");
request.source(new SearchSourceBuilder().query(QueryBuilders.termQuery("age", 40)));
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
System.out.println(hits.getTotalHits());
System.out.println(response.getTook());
for ( SearchHit hit : hits ) {
System.out.println(hit.getSourceAsString());
}
//关闭客户端
esClient.close();
}
}
分页查询
json
/**
* @Author wcy
* @Description //高级查询
* @Date 10:15 2022-12-02
* @Param
**/
public class ESTest_Doc_Query {
public static void main(String[] args) throws IOException {
//创建ES客户端
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("ip",9200,"http")));
//1.分页查询
SearchRequest request = new SearchRequest();
request.indices("user");
SearchSourceBuilder builder = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
// (当前页码-1)*每页显示数据条数
builder.from(2);
builder.size(2);
request.source(builder);
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
System.out.println(hits.getTotalHits());
System.out.println(response.getTook());
for ( SearchHit hit : hits ) {
System.out.println(hit.getSourceAsString());
}
//关闭客户端
esClient.close();
}
}
操作结果:
数据排序
java/**
* @Author wcy
* @Description //高级查询
* @Date 10:15 2022-12-02
* @Param
**/
public class ESTest_Doc_Query {
public static void main(String[] args) throws IOException {
//创建ES客户端
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("ip",9200,"http")));
//1.排序查询
SearchRequest request = new SearchRequest();
request.indices("user");
SearchSourceBuilder builder = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
//
builder.sort("age", SortOrder.DESC);
request.source(builder);
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
System.out.println(hits.getTotalHits());
System.out.println(response.getTook());
for (SearchHit hit : hits ) {
System.out.println(hit.getSourceAsString());
}
//关闭客户端
esClient.close();
}
}
过滤字段
java
/**
* @Author wcy
* @Description //高级查询
* @Date 10:15 2022-12-02
* @Param
**/
public class ESTest_Doc_Query {
public static void main(String[] args) throws IOException {
//创建ES客户端
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("ip",9200,"http")));
// 1. 过滤字段
SearchRequest request = new SearchRequest();
request.indices("user");
SearchSourceBuilder builder = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
//
String[] excludes = {"age"};
String[] includes = {};
builder.fetchSource(includes, excludes);
request.source(builder);
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
System.out.println(hits.getTotalHits());
System.out.println(response.getTook());
for ( SearchHit hit : hits ) {
System.out.println(hit.getSourceAsString());
}
//关闭客户端
esClient.close();
}
}
组合查询
java
/**
* @Author wcy
* @Description //高级查询
* @Date 10:15 2022-12-02
* @Param
**/
public class ESTest_Doc_Query {
public static void main(String[] args) throws IOException {
//创建ES客户端
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("ip",9200,"http")));
// 1. 组合查询
SearchRequest request = new SearchRequest();
request.indices("user");
SearchSourceBuilder builder = new SearchSourceBuilder();
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
//必须满足 相等于
boolQueryBuilder.mustNot(QueryBuilders.matchQuery("sex", "女"));
boolQueryBuilder.should(QueryBuilders.matchQuery("age", 50));
boolQueryBuilder.should(QueryBuilders.matchQuery("age", 40));
builder.query(boolQueryBuilder);
request.source(builder);
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
System.out.println(hits.getTotalHits());
System.out.println(response.getTook());
for ( SearchHit hit : hits ) {
System.out.println(hit.getSourceAsString());
}
//关闭客户端
esClient.close();
}
}
范围查询
java
/**
* @Author wcy
* @Description //高级查询
* @Date 10:15 2022-12-02
* @Param
**/
public class ESTest_Doc_Query {
public static void main(String[] args) throws IOException {
//创建ES客户端
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("ip",9200,"http")));
// 1. 范围查询
SearchRequest request = new SearchRequest();
request.indices("user");
SearchSourceBuilder builder = new SearchSourceBuilder();
RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("age");
rangeQuery.gte(30);
rangeQuery.lt(50);
builder.query(rangeQuery);
request.source(builder);
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
System.out.println(hits.getTotalHits());
System.out.println(response.getTook());
for ( SearchHit hit : hits ) {
System.out.println(hit.getSourceAsString());
}
//关闭客户端
esClient.close();
}
}
模糊查询
java
/**
* @Author wcy
* @Description //高级查询
* @Date 10:15 2022-12-02
* @Param
**/
public class ESTest_Doc_Query {
public static void main(String[] args) throws IOException {
//创建ES客户端
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("ip",9200,"http")));
// 1. 模糊查询
SearchRequest request = new SearchRequest();
request.indices("user");
SearchSourceBuilder builder = new SearchSourceBuilder();
builder.query(QueryBuilders.fuzzyQuery("name", "wangwu").fuzziness(Fuzziness.ONE));
request.source(builder);
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
System.out.println(hits.getTotalHits());
System.out.println(response.getTook());
for ( SearchHit hit : hits ) {
System.out.println(hit.getSourceAsString());
}
//关闭客户端
esClient.close();
}
}
深分页查询
java
public class ESTest_Doc_Search09 {
public static void main(String[] args) throws IOException {
Map<String, Object> map1 = searchByScrollPage("wangwu", null, 1);
System.out.println(map1.get("content"));
String scrollId = map1.get("scroll_id")+"";
Map<String, Object> map2 = searchByScrollPage("wangwu", scrollId, 1);
System.out.println(map2.get("content"));
}
public static Map<String, Object> searchByScrollPage(String keywords, String scrollId, int pageSize) throws IOException {
SearchResponse searchResponse = null;
//创建ES客户端
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("ip",9200,"http")));
if(scrollId == null) {
// 1.构建SearchRequest检索请求
// 专门用来进行全文检索、关键字检索的API
SearchRequest searchRequest = new SearchRequest("user");
// 2.创建一个SearchSourceBuilder专门用于构建查询条件
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
// 3.模糊查询字段
SearchSourceBuilder builder = new SearchSourceBuilder();
builder.query(QueryBuilders.fuzzyQuery("name", keywords).fuzziness(Fuzziness.ONE));
searchRequest.source(builder);
// 每页显示多少条
searchSourceBuilder.size(pageSize);
// 4.调用SearchRequest.source将查询条件设置到检索请求
searchRequest.source(searchSourceBuilder);
//--------------------------
// 设置scroll查询
//--------------------------
searchRequest.scroll(TimeValue.timeValueMinutes(5));
// 5.执行RestHighLevelClient.search发起请求
searchResponse = esClient.search(searchRequest, RequestOptions.DEFAULT);
}
// 第二次查询的时候,直接通过scroll id查询数据
else {
SearchScrollRequest searchScrollRequest = new SearchScrollRequest(scrollId);
searchScrollRequest.scroll(TimeValue.timeValueMinutes(5));
// 使用RestHighLevelClient发送scroll请求
searchResponse = esClient.scroll(searchScrollRequest, RequestOptions.DEFAULT);
}
//--------------------------
// 迭代ES响应的数据
//--------------------------
SearchHit[] hitArray = searchResponse.getHits().getHits();
// 6.遍历结果
ArrayList<User> userArrayList = new ArrayList<>();
for (SearchHit documentFields : hitArray) {
// 1)获取命中的结果
String json = documentFields.getSourceAsString();
// 2)将JSON字符串转换为对象
User user = JSONObject.parseObject(json, User.class);
// 3)使用SearchHit.getId设置文档ID
user.setId(documentFields.getId());
userArrayList.add(user);
}
// 8. 将结果封装到Map结构中(带有分页信息)
// a) total -> 使用SearchHits.getTotalHits().value获取到所有的记录数
// b) content -> 当前分页中的数据
long totalNum = searchResponse.getHits().getTotalHits().value;
HashMap hashMap = new HashMap();
hashMap.put("scroll_id", searchResponse.getScrollId());
hashMap.put("content", userArrayList);
return hashMap;
}
}
高亮查询
java
/**
* @Author wcy
* @Description //高亮查询
* @Date 10:15 2022-12-02
* @Param
**/
public class ESTest_Doc_Query {
public static void main(String[] args) throws IOException {
//创建ES客户端
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("ip",9200,"http")));
// 1. 高亮查询
SearchRequest request = new SearchRequest();
request.indices("user");
SearchSourceBuilder builder = new SearchSourceBuilder();
TermsQueryBuilder termsQueryBuilder = QueryBuilders.termsQuery("name", "wangwu1");
HighlightBuilder highlightBuilder = new HighlightBuilder();
highlightBuilder.preTags("<font color='red'>");
highlightBuilder.postTags("</font>");
highlightBuilder.field("name");
builder.highlighter(highlightBuilder);
builder.query(termsQueryBuilder);
request.source(builder);
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
System.out.println(hits.getTotalHits());
System.out.println(response.getTook());
for ( SearchHit hit : hits ) {
System.out.println(hit.getSourceAsString());
//打印高亮结果
Map<String, HighlightField> highlightFields = hit.getHighlightFields();
System.out.println(highlightFields);
}
//关闭客户端
esClient.close();
}
}
聚合查询
最大年龄:
java
public class ESTest_Doc_Search11 {
public static void main(String[] args) throws IOException {
//创建ES客户端
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("ip",9200,"http")));
// 1. 聚合查询
SearchRequest request = new SearchRequest();
request.indices("user");
SearchSourceBuilder builder = new SearchSourceBuilder();
AggregationBuilder aggregationBuilder = AggregationBuilders.max("maxAge").field("age");
builder.aggregation(aggregationBuilder);
request.source(builder);
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
Aggregations aggregations = response.getAggregations();
SearchHits hits = response.getHits();
ParsedMax max = aggregations.get("maxAge");
System.out.println(max.getValue());
for ( SearchHit hit : hits ) {
System.out.println(hit.getSourceAsString());
}
//关闭客户端
esClient.close();
}
}
}
分组查询
java
public class ESTest_Doc_Search12 {
public static void main(String[] args) throws IOException {
//创建ES客户端
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("ip",9200,"http")));
// 1. 分组查询
SearchRequest request = new SearchRequest();
request.indices("user");
SearchSourceBuilder builder = new SearchSourceBuilder();
AggregationBuilder aggregationBuilder = AggregationBuilders.terms("ageGroup").field("age");
builder.aggregation(aggregationBuilder);
request.source(builder);
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
Aggregations aggregations = response.getAggregations();
SearchHits hits = response.getHits();
ParsedLongTerms terms = aggregations.get("ageGroup");
List<? extends Terms.Bucket> buckets = terms.getBuckets();
for(Terms.Bucket bucket : buckets){
System.out.println("age:"+bucket.getKey()+" count:"+bucket.getDocCount());
}
for ( SearchHit hit : hits ) {
System.out.println(hit.getSourceAsString());
}
//关闭客户端
esClient.close();
}
}
二 Elasticsearch-集成springboot
1 Spring Data框架介绍
Spring Data 是一个用于简化数据库、非关系型数据库、索引库访问,并支持云服务的开源框架。其主要目标是使得对数据的访问变得方便快捷,并支持 map-reduce 框架和云计算数据服务。 Spring Data 可以极大的简化 JPA(Elasticsearch)的写法,可以在几乎不用写实现的情况下,实现对数据的访问和操作。除了 CRUD 外,还包括如分页、排序等一些常用的功能。
Spring Data官方网站:https://spring.io/projects/spring-data
2 Spring Data Elasticsearch介绍
Spring Data Elasticsearch 基于 spring data API 简化 Elasticsearch 操作,将原始操作Elasticsearch 的客户端 API 进行封装 。Spring Data 为 Elasticsearch 项目提供集成搜索引擎。Spring Data Elasticsearch POJO 的关键功能区域为中心的模型与 Elastichsearch 交互文档和轻松地编写一个存储索引库数据访问层。
Spring Data Elasticsearch官方网站: https://spring.io/projects/spring-data-elasticsearch
maven配置:
xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.16</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
<version>2.3.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
<version>2.3.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>2.3.6.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-test</artifactId>
<version>2.3.6.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.1</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.2.11.RELEASE</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
3. 配置准备
1.修改配置文件applcation.properties
properties
# es服务地址
elasticsearch.host=ip
# es服务端口
elasticsearch.port=9200
# 配置日志级别,开启debug日志
logging.level.com.lx.es=debug
2.实体类
java
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Document(indexName = "product", shards = 3, replicas = 1) //指定索引名称,主分片数量,副本数量
public class Product {
/**
* type : 字段数据类型
* analyzer : 分词器类型
* index : 是否索引(默认:true)
* Keyword : 短语,不进行分词
*/
/**
* 主键id
*/
@Id
private Long id;
/**
* 商品名称
*/
@Field(type = FieldType.Text)
private String title;
/**
* 商品分类
*/
@Field(type = FieldType.Keyword)
private String category;
/**
* 商品价格
*/
@Field(type = FieldType.Double)
private Double price;
/**
* 商品照片
*/
@Field(type = FieldType.Keyword, index = false)
private String images;
}
3.配置类
-
ElasticsearchRestTemplate 是 spring-data-elasticsearch 项目中的一个类,和其他 spring 项目中的 template类似。
-
在新版的 spring-data-elasticsearch 中,ElasticsearchRestTemplate 代替了原来的 ElasticsearchTemplate。原因是 ElasticsearchTemplate 基于 TransportClient,TransportClient 即将在 8.x 以后的版本中移除。所以,我们推荐使用 ElasticsearchRestTemplate。
-
ElasticsearchRestTemplate 基 于 RestHighLevelClient 客户端的。需要自定义配置类,继承AbstractElasticsearchConfiguration,并实现 elasticsearchClient()抽象方法,创建 RestHighLevelClient 对象。
java
@ConfigurationProperties(prefix = "elasticsearch")
@Configuration
@Data
public class ElasticsearchConfig extends AbstractElasticsearchConfiguration {
private String host ;
private Integer port ;
//重写父类方法
@Override
public RestHighLevelClient elasticsearchClient() {
RestClientBuilder builder = RestClient.builder(new HttpHost(host, port));
RestHighLevelClient restHighLevelClient = new RestHighLevelClient(builder);
return restHighLevelClient;
}
}
4.DAO数据访问对象
java
@Repository
public interface ProductDao extends ElasticsearchRepository<Product,Long> {
}
4.实战操作
创建索引
其实启动项目的时候就会帮我们创建索引
删除索引
java
@Test
public void deleteIndex(){
boolean flg = elasticsearchRestTemplate.deleteIndex(Product.class);
System.out.println("删除索引 = " + flg);
}
新增文档
java
@Test
public void save(){
Product product = new Product();
product.setId(100001L);
product.setTitle("华为手机");
product.setCategory("手机");
product.setPrice(2999.0);
product.setImages("http://www.huawei/hw.jpg");
productDao.save(product);
}
修改文档
java
@Test
public void update(){
Product product = new Product();
product.setId(100001L);
product.setTitle("小米手机");
product.setCategory("手机");
product.setPrice(9999.0);
product.setImages("http://www.xiaomi/xm.jpg");
productDao.save(product);
}
根据id查询文档
java
//根据 id 查询
@Test
public void findById(){
Product product = productDao.findById(100001L).get();
System.out.println(product);
}
查询所有文档
java
//查询所有
@Test
public void findAll(){
Iterable<Product> products = productDao.findAll();
for (Product product : products) {
System.out.println(product);
}
}
删除文档
java
//删除
@Test
public void delete(){
Product product = new Product();
product.setId(100001L);
productDao.delete(product);
}
批量新增
java
//批量新增
@Test
public void saveAll(){
List<Product> productList = new ArrayList<>();
for (int i = 0; i < 10; i++) {
Product product = new Product();
product.setId(Long.valueOf(i));
product.setTitle("小米手机"+"["+i+"]");
product.setCategory("手机");
product.setPrice(1999.0+i);
product.setImages("http://www.xiaomi/xm.jpg");
productList.add(product);
}
productDao.saveAll(productList);
}
分页查询
java
//分页查询
@Test
public void findByPageable(){
//设置排序(排序方式,正序还是倒序,排序的 id)
Sort sort = Sort.by(Sort.Direction.DESC,"id");
int currentPage=0;//当前页,第一页从 0 开始,1 表示第二页
int pageSize = 5;//每页显示多少条
//设置查询分页
PageRequest pageRequest = PageRequest.of(currentPage, pageSize,sort);
//分页查询
Page<Product> productPage = productDao.findAll(pageRequest);
for (Product Product : productPage.getContent()) {
System.out.println(Product);
}
}
精确查询
java
/**
* term 查询
* search(termQueryBuilder) 调用搜索方法,参数查询构建器对象
*/
@Test
public void termQuery(){
TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("category", "手机");
Iterable<Product> products = productDao.search(termQueryBuilder);
for (Product product : products) {
System.out.println(product);
}
}
精确加分页查询
java
@Test
public void termQueryByPage(){
int currentPage= 0 ;
int pageSize = 5;
//设置查询分页
PageRequest pageRequest = PageRequest.of(currentPage, pageSize);
TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("category", "手机");
Iterable<Product> products =
productDao.search(termQueryBuilder,pageRequest);
for (Product product : products) {
System.out.println(product);
}
}
nt pageSize = 5;//每页显示多少条
//设置查询分页
PageRequest pageRequest = PageRequest.of(currentPage, pageSize,sort);
//分页查询
Page productPage = productDao.findAll(pageRequest);
for (Product Product : productPage.getContent()) {
System.out.println(Product);
}
}
### 精确查询
```java
/**
* term 查询
* search(termQueryBuilder) 调用搜索方法,参数查询构建器对象
*/
@Test
public void termQuery(){
TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("category", "手机");
Iterable<Product> products = productDao.search(termQueryBuilder);
for (Product product : products) {
System.out.println(product);
}
}
精确加分页查询
java
@Test
public void termQueryByPage(){
int currentPage= 0 ;
int pageSize = 5;
//设置查询分页
PageRequest pageRequest = PageRequest.of(currentPage, pageSize);
TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("category", "手机");
Iterable<Product> products =
productDao.search(termQueryBuilder,pageRequest);
for (Product product : products) {
System.out.println(product);
}
}
🌟至此本篇就结束了,下一篇将介绍如何使用ELK进行日志收集以及项目中实战使用的操作