Elasticsearch软件是由Java语言开发的,所以也可以通过JavaAPI的方式对Elasticsearch服务进行访问。
ES 官方提供了三种 Java API 接口,分别是 TransportClient、Java Low Level REST Client、 Java High Level REST Client。 其中 TransportClient 在 ES 7.x 版本中被标记为过时,并且将在 ES 8.x 版本中完全移除。 原因是 ES 版本迭代较快,TransportClient 使用了特定的传输协议,如果其版本与 ES 实例版 本不一致则可能导致兼容性问题。ES 官方提供了向后兼容的 Java Low Level REST Client, 并在此基础上提供了功能更多的 J a v a H i g h L e v e l R e s t C l i e n t \textcolor{red}{JavaHighLevelRestClient} JavaHighLevelRestClient ,因此使用 Java High Level REST Clientl来调用Elasticsearch接口。
1 导入依赖
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!-- 请求传输 json格式的数据-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.15.2</version>
</dependency>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>7.8.0</version>
</dependency>
<!-- Java High Level REST Client-->
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.8.0</version>
</dependency>
<!-- elasticsearch 底层依赖log4j的-->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.7</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.7</version>
</dependency>
</dependencies>
2 索引操作
2.1 创建索引
创建名为post的索引 ,使用CreateIndexRequest,等价于 PUT请求 h t t p : / / l o c a l h o s t : 9200 / p o s t \textcolor{red}{http://localhost:9200/post} http://localhost:9200/post
public class RestHighLevelClient_IndexCreate {
//索引名称
private static final String INDEX_NAME="post";
public static void main(String[] args) throws IOException {
//创建es客户端
RestHighLevelClient client=new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
//判断索引是否已存在
GetIndexRequest getIndexRequest=new GetIndexRequest(INDEX_NAME);
boolean exists = client.indices().exists(getIndexRequest, RequestOptions.DEFAULT);
if(!exists){
//创建索引的请求 指定索引的名字
CreateIndexRequest request=new CreateIndexRequest(INDEX_NAME);
//使用客户端向指定es服务器发送创建索引的请求,获得响应
CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);
//响应状态
boolean acknowledged = response.isAcknowledged();
if(acknowledged){
System.out.println("创建索引成功");
}
}else{
System.out.println("当前索引已存在");
}
//关闭es客户端
client.close();
}
}
2.3 查询索引
查询名为post的索引信息,等价于发送Get请求 h t t p : / / l o c a l h o s t : 9200 / p o s t \textcolor{red}{http://localhost:9200/post} http://localhost:9200/post
public class RestHighLevelClient_IndexSearch {
//索引名称
private static final String INDEX_NAME="post";
public static void main(String[] args) throws IOException {
//创建es客户端
RestHighLevelClient client=new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
//获得索引的请求 指定索引的名字
GetIndexRequest request=new GetIndexRequest(INDEX_NAME);
//使用客户端向指定es服务器发送查询索引为post的请求的请求,获得响应
GetIndexResponse response = client.indices().get(request, RequestOptions.DEFAULT);
//打印响应结果
System.out.println(response.getAliases());
System.out.println(response.getMappings());
System.out.println(response.getSettings());
//关闭es客户端
client.close();
}
}
2.4 删除索引
删除名为post的索引,等价于发送Delete请求 h t t p : / / l o c a l h o s t : 9200 / p o s t \textcolor{red}{http://localhost:9200/post} http://localhost:9200/post
public class RestHighLevelClient_IndexDelete {
//索引名称
private static final String INDEX_NAME="post";
public static void main(String[] args) throws IOException {
//创建es客户端
RestHighLevelClient client=new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
//判断索引是否已存在
GetIndexRequest getIndexRequest=new GetIndexRequest(INDEX_NAME);
boolean exists = client.indices().exists(getIndexRequest, RequestOptions.DEFAULT);
if(exists){
DeleteIndexRequest request=new DeleteIndexRequest(INDEX_NAME);
AcknowledgedResponse response = client.indices().delete(request, RequestOptions.DEFAULT);
if(response.isAcknowledged()){
System.out.println("成功删除索引");
}
}else{
System.out.println("当前索引不存在,无法删除");
}
//关闭es客户端
client.close();
}
}
3 文档操作
public class Post {
/**
* 文章id
*/
private Integer Id;
/**
* 文章作者
*/
private String author;
/**
* 创建时间
*/
private Date createTime;
/**
* 文章标题
*/
private String title;
/**
* 文章内容
*/
private String content;
}
文档需要操作的字段信息如上 ,包含文章Id,文章作者、创建时间、文章标题、内容等
3.1 新增文档数据
//索引名称
private static final String INDEX_NAME="post";
public static void main(String[] args) throws IOException {
//创建es客户端
RestHighLevelClient client=new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
IndexRequest request=new IndexRequest();
request.index(INDEX_NAME).id("1001");
//定义需要的插入的文档数据
Post post=new Post();
post.setId(3);
post.setAuthor("LuisTom");
post.setCreateTime(new Date());
post.setTitle("自定义字段映射");
post.setContent("尽管在很多情况下基本字段数据类型已经够用,但你经常需要为单独字段自定义映射,特别是\n" +
"字符串字段。自定义映射允许你执行下面的操作:\n" +
"\uF06C 全文字符串字段和精确值字符串字段的区别\n" +
"\uF06C 使用特定语言分析器\n" +
"\uF06C 优化字段以适应部分匹配\n" +
"\uF06C 指定自定义数据格式\n" +
"\uF06C 还有更多");
//序列化成json文档
ObjectMapper mapper=new ObjectMapper();
String postJson = mapper.writeValueAsString(post);
//数据传输的post对象序列化成json的内容信息
request.source(postJson, XContentType.JSON);
//传输新增文档的响应response
IndexResponse response= client.index(request,RequestOptions.DEFAULT);
//打印响应结果
System.out.println(response.toString());
//关闭es客户端
client.close();
}
}
3.2 查询文档
等价于发送Get请求 h t t p : / / l o c a l h o s t : 9200 / p o s t / d o c / 1001 \textcolor{red}{http://localhost:9200/post/ _doc/1001} http://localhost:9200/post/doc/1001
public class RestHighLevelClient_DocSearch {
//索引名称
private static final String INDEX_NAME="post";
public static void main(String[] args) throws IOException {
//创建es客户端
RestHighLevelClient client=new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
//获得索引post上 id为1001的文档信息
GetRequest request=new GetRequest(INDEX_NAME,"1001");
GetResponse response = client.get(request, RequestOptions.DEFAULT);
String source = response.getSourceAsString();
System.out.println(response);
//关闭es客户端
client.close();
}
}
3.3 搜索文档
通过SearchSourceBuilder 构建不同的搜索对象,去Index上搜索文档信息文章来源:https://www.toymoban.com/news/detail-544534.html
public class RestHighLevelClient_DocQuery {
//索引名称
private static final String INDEX_NAME = "post";
public static void main(String[] args) throws IOException {
//创建es客户端
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http"))
);
SearchRequest request = new SearchRequest(INDEX_NAME);
//构建查询对象
SearchSourceBuilder builder = new SearchSourceBuilder();
//builder.query(QueryBuilders.matchQuery("author","lyf")); //author字段匹配 lyf 使用matchQuery
//builder.query(QueryBuilders.termQuery("author","lyf")); //author字段匹配 lyf 使用termQuery
//BoolQueryBuilder boolQueryBuilder=new BoolQueryBuilder();
//boolQueryBuilder.must(QueryBuilders.matchQuery("author","lyf"))
// .must(QueryBuilders.matchQuery("id","1"));
//builder.query(boolQueryBuilder); //组合条件查询 BoolQueryBuilder
//builder.query(QueryBuilders.rangeQuery("id").gte(2).lte(3)); //范围查询,id>=2 and id<=3的文档数据 rangeQuery
builder.query(QueryBuilders.matchPhraseQuery("title","Elasticsearch")); //模糊查询
//分页查询 每页两条,查询第一页数据
//from =(当前页面-1)*size
builder.from(0);
builder.size(2);
//过滤筛选字段
String[] excludes = {}; //需要排除的字段
String[] includes = {"id", "title", "author"};//需要筛选的字段
builder.fetchSource(includes, excludes);
builder.sort("id", SortOrder.DESC);//根据id倒序排
//传入查询对象
request.source(builder);
//获得查询响应对象
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
for (SearchHit hit : hits) {
//遍历打印查询后的数据
System.out.println(hit.getSourceAsString());
}
//关闭es客户端
client.close();
}
}
3.4 删除文档
等价于发送Delete请求 h t t p : / / l o c a l h o s t : 9200 / p o s t / d o c / 1001 \textcolor{red}{http://localhost:9200/post/ _doc/1001} http://localhost:9200/post/doc/1001文章来源地址https://www.toymoban.com/news/detail-544534.html
public class RestHighLevelClient_DocDelete {
//索引名称
private static final String INDEX_NAME="post";
public static void main(String[] args) throws IOException {
//创建es客户端
RestHighLevelClient client=new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
//删除post id为1001的文档的请求
DeleteRequest request=new DeleteRequest(INDEX_NAME,"1001");
DeleteResponse response = client.delete(request, RequestOptions.DEFAULT);
System.out.println(response);
//关闭es客户端
client.close();
}
}
3.5 批量新增文档
public class RestHighLevelClient_DocBatchAdd {
//索引名称
private static final String INDEX_NAME="post";
public static void main(String[] args) throws IOException {
//创建es客户端
RestHighLevelClient client=new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
ObjectMapper mapper=new ObjectMapper();
//定义需要的插入的文档数据
Post post_1=new Post();
post_1.setId(1);
post_1.setAuthor("lyf");
post_1.setCreateTime(new Date());
post_1.setTitle("Elasticsearch介绍");
post_1.setContent("Elasticsearch 是一款高度可伸缩的全文检索和分析引擎。用于近实时存储、搜索和分析大量数\n" +
"据。在 Elastic APM 中,Elasticsearch 用于存储和聚合性能监控指标。");
String str_1=mapper.writeValueAsString(post_1);
Post post_2=new Post();
post_2.setId(2);
post_2.setAuthor("lyf");
post_2.setCreateTime(new Date());
post_2.setTitle("Mapping");
post_2.setContent("映射(mapping)就像数据库中的 Schema ,描述了文档可能具有的字段或属性、每个字段的\n" +
"数据类型,比如 Text,Keyword,Integer 或 Date ,以及 Lucene 是如何索引和存储这些字\n" +
"段的。");
String str_2=mapper.writeValueAsString(post_2);
//批量新增请求
BulkRequest request=new BulkRequest();
request.add(new IndexRequest().index(INDEX_NAME).id("1001").source(str_1,XContentType.JSON));
request.add(new IndexRequest().index(INDEX_NAME).id("1002").source(str_2,XContentType.JSON));
BulkResponse response = client.bulk(request, RequestOptions.DEFAULT);
BulkItemResponse[] items = response.getItems();
for (BulkItemResponse re:items){
//遍历打印响应结果信息
System.out.println(re.toString());
}
//关闭es客户端
client.close();
}
}
到了这里,关于Elasticsearch(3)——JavaAPI操作Elasticsearch的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!