ElasticSearch Java API
Posted Juno3550
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ElasticSearch Java API相关的知识,希望对你有一定的参考价值。
SpringBoot 整合 ES
1)引入 ElasticSearch 相关坐标:
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.4.0</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-client</artifactId>
<version>7.4.0</version>
</dependency>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>7.4.0</version>
</dependency>
2)ElasticSearchConfig.java(ES 配置类):
package com.example.es_demo.config;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@ConfigurationProperties(prefix = "elasticsearch")
public class EsConfig
private String host;
private int port;
public String getHost()
return host;
public void setHost(String host)
this.host = host;
public int getPort()
return port;
public void setPort(int port)
this.port = port;
@Bean
public RestHighLevelClient client()
return new RestHighLevelClient(RestClient.builder(
new HttpHost(host, port, "http")
));
3)测试类:
- 注意:使用 @Autowired 注入 RestHighLevelClient 时如果报红线,则是因为配置类所在的包和测试类所在的包,两者包名不一致造成的。
package com.example.es_demo;
import org.elasticsearch.client.RestHighLevelClient;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class EsDemoApplicationTests
@Autowired
RestHighLevelClient client;
@Test
void contextLoads()
System.out.println(client);
操作索引
创建索引
/**
* 添加索引
*/
@Test
public void addIndex() throws IOException
// 1.使用client获取操作索引对象
IndicesClient indices = client.indices();
// 2.创建索引
CreateIndexRequest createIndexRequest = new CreateIndexRequest("index1");
CreateIndexResponse createIndexResponse = indices.create(createIndexRequest, RequestOptions.DEFAULT);
// 3.根据返回值判断结果
System.out.println(createIndexResponse.isAcknowledged());
/**
* 添加索引,并添加映射
*/
@Test
public void addIndexAndMapping() throws IOException
// 1.使用client获取操作索引对象
IndicesClient indices = client.indices();
// 2.添加索引
CreateIndexRequest createIndexRequest = new CreateIndexRequest("index2");
// 3.添加mappings
String mapping = "\\n" +
" \\"properties\\" : \\n" +
" \\"address\\" : \\n" +
" \\"type\\" : \\"text\\",\\n" +
" \\"analyzer\\" : \\"ik_max_word\\"\\n" +
" ,\\n" +
" \\"age\\" : \\n" +
" \\"type\\" : \\"long\\"\\n" +
" ,\\n" +
" \\"name\\" : \\n" +
" \\"type\\" : \\"keyword\\"\\n" +
" \\n" +
" \\n" +
" ";
createIndexRequest.mapping(mapping, XContentType.JSON);
CreateIndexResponse createIndexResponse = indices.create(createIndexRequest, RequestOptions.DEFAULT);
// 4.根据返回值判断结果
System.out.println(createIndexResponse.isAcknowledged());
查询索引
/**
* 查询索引
*/
@Test
public void queryIndex() throws IOException
IndicesClient indices = client.indices();
GetIndexRequest getRequest=new GetIndexRequest("index2");
GetIndexResponse response = indices.get(getRequest, RequestOptions.DEFAULT);
Map<String, MappingMetaData> mappings = response.getMappings();
for (String key : mappings.keySet())
System.out.println(key+"==="+mappings.get(key).getSourceAsMap());
// index2===properties=address=analyzer=ik_max_word, type=text, name=type=keyword, age=type=long
/**
* 判断索引是否存在
*/
@Test
public void existIndex() throws IOException
IndicesClient indices = client.indices();
GetIndexRequest getIndexRequest=new GetIndexRequest("index1");
boolean exists = indices.exists(getIndexRequest, RequestOptions.DEFAULT);
System.out.println(exists);
删除索引
/**
* 删除索引
*/
@Test
public void deleteIndex() throws IOException
IndicesClient indices = client.indices();
DeleteIndexRequest deleteRequest=new DeleteIndexRequest("index2");
AcknowledgedResponse delete = indices.delete(deleteRequest, RequestOptions.DEFAULT);
// 返回是否删除成功
System.out.println(delete.isAcknowledged());
操作文档
引入阿里巴巴的 JSON 格式转换库:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.4</version>
</dependency>
添加文档
注意:在仅有索引的情况下也可以添加文档,且在有映射的情况下也可以新增字段,两者操作均会自动添加默认类型。
/**
* 添加文档,使用map作为数据
*/
@Test
public void addDoc() throws IOException
// map数据
Map data = new HashMap();
data.put("address", "北京昌平");
data.put("name", "大胖");
data.put("age", 20);
// 获取操作文档的对象
IndexRequest request = new IndexRequest("index2").id("1").source(data);
// 添加数据,获取结果
IndexResponse response = client.index(request, RequestOptions.DEFAULT);
//打印响应结果
System.out.println(response.getId());
/**
* 添加文档,使用对象作为数据
*/
@Test
public void addDoc2() throws IOException
// 对象数据
Person p = new Person();
p.setId("3");
p.setName("小胖3333");
p.setAge(30);
p.setAddress("广东深圳");
p.setHobby("basketball");
// 将对象转为json
String data = JSON.toJSONString(p);
// 获取操作文档的对象
IndexRequest request = new IndexRequest("index2").id(p.getId()).source(data, XContentType.JSON);
// 添加数据,获取结果
IndexResponse response = client.index(request, RequestOptions.DEFAULT);
// 打印响应结果
System.out.println(response.getId());
修改文档
/**
* 修改文档:添加文档时,如果id存在则修改,id不存在则添加
*/
@Test
public void UpdateDoc() throws IOException
Person person=new Person();
person.setId("2");
person.setName("李四");
person.setAge(20);
person.setAddress("北京三环车王");
String data = JSON.toJSONString(person);
IndexRequest request=new IndexRequest("itcast").id(person.getId()).source(data,XContentType.JSON);
IndexResponse response = client.index(request, RequestOptions.DEFAULT);
System.out.println(response.getId());
查询文档
/**
* 根据id查询文档
*/
@Test
public void getDoc() throws IOException
//设置查询的索引、文档
GetRequest indexRequest=new GetRequest("itcast","2");
GetResponse response = client.get(indexRequest, RequestOptions.DEFAULT);
System.out.println(response.getSourceAsString());
删除文档
/**
* 根据id删除文档
*/
@Test
public void delDoc() throws IOException
//设置要删除的索引、文档
DeleteRequest deleteRequest=new DeleteRequest("itcast","1");
DeleteResponse response = client.delete(deleteRequest, RequestOptions.DEFAULT);
System.out.println(response.getId());
bulk 批量操作
/**
* Bulk 批量操作
*/
@Test
public void test2() throws IOException
// 创建bulkrequest对象,整合所有操作
BulkRequest bulkRequest =new BulkRequest();
// 1. 删除5号记录
DeleteRequest deleteRequest=new DeleteRequest("person1", "5");
bulkRequest.add(deleteRequest);
// 2. 添加6号记录
Map<String, Object> map=new HashMap<>();
map.put("name", "六号");
IndexRequest indexRequest=new IndexRequest("person1").id("6").source(map);
bulkRequest.add(indexRequest);
// 3. 修改3号记录 名称为 “三号”
Map<String, Object> mapUpdate=new HashMap<>();
mapUpdate.put("name", "三号");
UpdateRequest updateRequest=new UpdateRequest("person1", "3").doc(mapUpdate);
bulkRequest.add(updateRequest);
// 执行批量操作
BulkResponse response = client.bulk(bulkRequest, RequestOptions.DEFAULT);
System.out.println(response.status());
以上是关于ElasticSearch Java API的主要内容,如果未能解决你的问题,请参考以下文章
[ElasticSearch]Java API 之 索引管理
Android Studio编译OsmAnd出现警告:GeoPointParserUtil.java使用或覆盖了已过时的 API。有关详细信息请使用-Xlint:deprecation重新编译(代码片
使用 Elasticsearch Java API 运行文本查询