ElasticSearch在JavaAPI中的操作(入门)
Posted 周大仙1
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ElasticSearch在JavaAPI中的操作(入门)相关的知识,希望对你有一定的参考价值。
目录
2.2.5 Java API 操作
ES软件是由Java语言开发的,所以也可以通过Java API的方式对ES服务进行访问
需要添加的依赖如下
<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>
(1)环境准备&创建ES客户端
package com.jt.test;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import java.io.IOException;
//es创建客户端对象
public class EsDemo1
public static void main(String[] args) throws IOException
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
System.out.println(client);
client.close();
(2)ES索引创建
package com.jt.test;
import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import java.io.IOException;
//Es索引创建
public class EsDemo2
public static void main(String[] args) throws IOException
//创建客户端对象
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http")));
// 创建索引 - 请求对象
CreateIndexRequest request = new CreateIndexRequest("root");
// 发送请求,获取响应
CreateIndexResponse response = client.indices().create(request,
RequestOptions.DEFAULT);
boolean acknowledged = response.isAcknowledged();
// 响应状态
System.out.println("操作状态 = " + acknowledged);
// 关闭客户端连接
client.close();
响应结果为:root索引创建完成
(3)ES索引&查询&删除
package com.jt.test;
import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexAction;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.client.indices.GetIndexResponse;
import java.io.IOException;
//Es索引 查询 删除
public class EsDemo3
public static void main(String[] args) throws IOException
// 创建客户端对象
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http")));
// 查询索引 - 请求对象
GetIndexRequest request = new GetIndexRequest("root");
// 发送请求,获取响应
GetIndexResponse response = client.indices().get(request,
RequestOptions.DEFAULT);
System.out.println("aliases:"+response.getAliases());
System.out.println("mappings:"+response.getMappings());
System.out.println("settings:"+response.getSettings());
//删除索引
// AcknowledgedResponse delete = delete(client);
// System.out.println(delete.isAcknowledged());
client.close();
public static AcknowledgedResponse delete(RestHighLevelClient client) throws IOException
DeleteIndexRequest request2 = new DeleteIndexRequest("root");
AcknowledgedResponse response2 = client.indices().delete(request2, RequestOptions.DEFAULT);
return response2;
查询结果为
如果想要删除索引,将上面注释取消即可
(4)文档 新增&修改
新增
package com.jt.popj;
import lombok.Data;
@Data
public class User
private String name;
private Integer age;
private String sex;
package com.jt.test;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jt.config.ConnectElasticsearch;
import com.jt.popj.User;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.common.xcontent.XContentType;
//新增
public class EsDemo5
public static void main(String[] args)
ConnectElasticsearch.connect(client ->
//新增文档 --请求对象
IndexRequest request = new IndexRequest();
//设置索引 唯一标识
request.index("root").id("1001");
//创建数据对象
User user = new User();
user.setAge(18);
user.setName("张飞");
user.setSex("男");
ObjectMapper objectMapper = new ObjectMapper();
String productJson = objectMapper.writeValueAsString(user);
//添加文档数据,格式为json
request.source(productJson, XContentType.JSON);
//客户端发送请求,获取相应对象
IndexResponse response = client.index(request, RequestOptions.DEFAULT);
System.out.println("索引:"+response.getIndex());
System.out.println("id:"+response.getId());
System.out.println("数据"+response.getResult());
);
修改数据
package com.jt.test;
import org.apache.http.HttpHost;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import java.io.IOException;
//修改数据
public class EsDemo6
public static void main(String[] args) throws IOException
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
//修改数据
UpdateRequest request = new UpdateRequest();
request.index("root").id("1001");
request.doc(XContentType.JSON,"sex","女");
UpdateResponse response = esClient.update(request , RequestOptions.DEFAULT);
System.out.println(response.getResult());
esClient.close();
检测修改的结果
package com.jt.test;
import org.apache.http.HttpHost;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.IndicesClient;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import java.io.IOException;
public class EsDemo7
public static void main(String[] args) throws IOException
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
GetRequest request = new GetRequest();
request.index("root").id("1001");
GetResponse reponse = esClient.get(request, RequestOptions.DEFAULT);
System.out.println(reponse.getSourceAsString());
esClient.close();
(5)文档的批量新增&批量删除
批量新增
package com.jt.test;
import org.apache.http.HttpHost;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import java.io.IOException;
//批量新增和批量删除
public class EsDemo8
public static void main(String[] args) throws IOException
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
BulkRequest request = new BulkRequest();
request.add(new IndexRequest().index("root").id("1002").source(XContentType.JSON,"name","刘备"));
request.add(new IndexRequest().index("root").id("1002").source(XContentType.JSON,"name","赵云"));
request.add(new IndexRequest().index("root").id("1002").source(XContentType.JSON,"name","关羽"));
BulkResponse response = esClient.bulk(request, RequestOptions.DEFAULT);
System.out.println(response.getTook());//花费的时间
System.out.println(response.getItems());//响应信息
esClient.close();
批量删除
package com.jt.test;
import org.apache.http.HttpHost;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import java.io.IOException;
//批量新增和批量删除
public class EsDemo8
public static void main(String[] args) throws IOException
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
BulkRequest request = new BulkRequest();
request.add(new DeleteRequest().index("root").id("1002"));
request.add(new DeleteRequest().index("root").id("1002"));
request.add(new DeleteRequest().index("root").id("1002"));
BulkResponse response = esClient.bulk(request, RequestOptions.DEFAULT);
System.out.println(response.getTook());//花费的时间
System.out.println(response.getItems());//响应信息
esClient.close();
(6)高级查询&全量查询
全量查询
package com.jt.test;
import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import java.io.IOException;
//高级查询&全量查询
public class EsDemo9
public static void main(String[] args) throws IOException
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
//查询数据
SearchRequest request = new SearchRequest();
request.indices("root");
//全量查询
request.source(new SearchSourceBuilder().query(QueryBuilders.matchAllQuery()));//全量匹配
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)
String sourceAsString = hit.getSourceAsString();
System.out.println(sourceAsString);
查询结果
(7)高级查询&分页查询&条件查询&字段查询
条件查询
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
//查询数据
SearchRequest request = new SearchRequest();
request.indices("root");
request.source(new SearchSourceBuilder().query(QueryBuilders.termQuery("age",26)));//查询条件:age=26
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
for (SearchHit hit:hits)
System.out.println(hit.getSourceAsString());
esClient.close();
//全量查询
分页查询
from()括号中的参数: (页码数-1)*每页显式的条数 也就是size里面的参数
排序
只需要在size().sort()就可以
包含和排除
响应结果
(8)高级查询&组合查询&范围查询
组合查询
package com.jt.test;
import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import java.io.IOException;
//高级查询&组合查询&范围查询
public class EsDemo11
public static void main(String[] args) throws IOException
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
//查询数据
SearchRequest request = new SearchRequest();
request.indices("root");
SearchSourceBuilder builder = new SearchSourceBuilder(); //创建查询构造器
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); //创建组合查询构造器
// boolQueryBuilder.must(QueryBuilders.matchQuery("age",25)); //must等价于and 两者都满足
// boolQueryBuilder.must(QueryBuilders.matchQuery("sex","男"));
// boolQueryBuilder.mustNot(QueryBuilders.matchQuery("sex","男"));//mustnot 两者都不满足
// boolQueryBuilder.mustNot(QueryBuilders.matchQuery("age",25));
boolQueryBuilder.should(QueryBuilders.matchQuery("sex","男"));//should等价于or 其中有一个条件满足就可以
boolQueryBuilder.should(QueryBuilders.matchQuery("age",25));
builder.query(boolQueryBuilder); //将组合构造器加入查询构造器
request.source(builder); //查询构造器加入查询请求
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
for (SearchHit hit:hits)
System.out.println(hit.getSourceAsString());
esClient.close();
范围查询
package com.jt.test;
import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import java.io.IOException;
//高级查询&组合查询&范围查询
public class EsDemo11
public static void main(String[] args) throws IOException
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
//查询数据
SearchRequest request = new SearchRequest();
request.indices("root");
SearchSourceBuilder builder = new SearchSourceBuilder(); //创建查询构造器
RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("age"); //范围查询rangeQuery,参数为字段
rangeQueryBuilder.gte(22);//>= 22
rangeQueryBuilder.lte(28);// <= 28
builder.query(rangeQueryBuilder); //将范围查询构造器加入查询构造器
request.source(builder); //查询构造器加入查询请求
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
for (SearchHit hit:hits)
System.out.println(hit.getSourceAsString());
esClient.close();
(9)高级查询&模糊查询&高亮查询
模糊查询
package com.jt.test;
import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.Fuzziness;
import org.elasticsearch.index.query.FuzzyQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import java.io.IOException;
//高级查询&模糊查询&高亮查询
public class EsDemo12
public static void main(String[] args) throws IOException
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
//查询数据
SearchRequest request = new SearchRequest();
request.indices("root");
SearchSourceBuilder builder = new SearchSourceBuilder(); //创建查询构造器
FuzzyQueryBuilder fuzzyQueryBuilder = QueryBuilders //模糊查询 Fuzziness.ONE 匹配多一个字符。比如:关羽1 x关羽 关x羽....
.fuzzyQuery("name", "关羽").fuzziness(Fuzziness.ONE);
builder.query(fuzzyQueryBuilder);
request.source(builder);
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
for (SearchHit hit:hits)
System.out.println(hit.getSourceAsString());
esClient.close();
高亮查询
package com.jt.test;
import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.Fuzziness;
import org.elasticsearch.index.query.FuzzyQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import java.io.IOException;
public class EsDemo12
public static void main(String[] args) throws IOException
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
//查询数据
SearchRequest request = new SearchRequest();
request.indices("root");
SearchSourceBuilder builder = new SearchSourceBuilder(); //创建查询构造器
TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("sex", "男");
HighlightBuilder highlightBuilder = new HighlightBuilder();//创建高亮构造器
highlightBuilder.preTags("<font color = 'red'>");
highlightBuilder.postTags("</font>");
highlightBuilder.field("sex");
builder.highlighter(highlightBuilder);//高亮构造器加入查询构造器中
builder.query(termQueryBuilder);
request.source(builder);
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
for (SearchHit hit:hits)
System.out.println(hit.getSourceAsString());
esClient.close();
(10)高级查询&聚合查询&分组查询
聚合查询
package com.jt.test;
import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.metrics.AvgAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import java.io.IOException;
//聚合查询和分组查询
public class EsDemo13
public static void main(String[] args) throws IOException
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
//查询数据
SearchRequest request = new SearchRequest();
request.indices("root");
SearchSourceBuilder builder = new SearchSourceBuilder(); //创建查询构造器
AggregationBuilder aggregationBuilder = AggregationBuilders.max("maxAge").field("age");//自定义最大值名字 maxAge
builder.aggregation(aggregationBuilder);
request.source(builder);
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
for (SearchHit hit:hits)
System.out.println(hit.getSourceAsString());
esClient.close();
查询结果
分组查询
package com.jt.test;
import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.metrics.AvgAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import java.io.IOException;
//聚合查询和分组查询
public class EsDemo13
public static void main(String[] args) throws IOException
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
//查询数据
SearchRequest request = new SearchRequest();
request.indices("root");
SearchSourceBuilder builder = new SearchSourceBuilder(); //创建查询构造器
// AggregationBuilder aggregationBuilder = AggregationBuilders.max("maxAge").field("age");//自定义最大值名字 maxAge
AggregationBuilder aggregationBuilder = AggregationBuilders.terms("ageGroup").field("age");//自定义最大值名字 maxAge
builder.aggregation(aggregationBuilder);
request.source(builder);
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
for (SearchHit hit:hits)
System.out.println(hit.getSourceAsString());
esClient.close();
查询结果为
以上是关于ElasticSearch在JavaAPI中的操作(入门)的主要内容,如果未能解决你的问题,请参考以下文章
Elasticsearch7.8.0版本入门——JavaAPI操作(索引操作)