之前我们介绍了elasticsearch的安装,这里我们实战一下,看下具体的java api如何操作。话不多说,直接开始
一、添加maven依赖
<dependency> <groupId>org.elasticsearch</groupId> <artifactId>elasticsearch</artifactId> <version>7.7.0</version> </dependency> <!-- https://mvnrepository.com/artifact/org.elasticsearch.client/elasticsearch-rest-high-level-client --> <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>elasticsearch-rest-high-level-client</artifactId> <version>7.7.0</version> </dependency>
二、代码的公共部分
RestHighLevelClient client = null;
@Before
public void init() {
client = new RestHighLevelClient(RestClient.builder(new HttpHost("192.168.31.20", 9200, "http")));
}
@After
public void destroy() {
try {
if (null != client) {
client.close();
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}三、创建与查看index
1)创建index
/**
* 创建一个索引
*
* @throws Exception
*/
@Test
public void createIndex() throws Exception {
CreateIndexRequest request = new CreateIndexRequest("test");
// 设置创建的索引的分片和副本数
request.settings(Settings.builder().put("index.number_of_shards", 2).put("index.number_of_replicas", 1));
// 设置初始化的mapping
String mapping = this.getMapping();
request.mapping(mapping,XContentType.JSON);
CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);
log.info("创建index索引的结果是:{}", JSON.toJSONString(response));
}/**
* 设置mapping
*
* @return
*/
private String getMapping() {
HashMap<String, Object> doc = new HashMap<String, Object>();
HashMap<String, Object> properties = new HashMap<String, Object>();
HashMap<String, Object> name = new HashMap<String, Object>();
name.put("type", "text");
HashMap<String, Object> model = new HashMap<String, Object>();
model.put("type", "keyword");
properties.put("name", name);
properties.put("model", model);
doc.put("properties", properties);
log.info("准备创建的mapping是:{}", JSON.toJSONString(doc));
return JSON.toJSONString(doc);
}2)查看index
/**
* 查看索引信息
*
* @throws IOException
*/
@Test
public void showIndex() throws IOException {
GetIndexRequest request = new GetIndexRequest();
request.indices("test");
GetIndexResponse response = client.indices().get(request, RequestOptions.DEFAULT);
log.info("查看对应索引的信息 aliases:{}", response.getAliases());
log.info("查看对应索引的信息 mapping:{}", JSON.toJSONString());
log.info("查看对应索引的信息 setting:{}", response.getSettings());
}四、插入数据
1)单条插入数据
@Test public void insertData() throws Exception { IndexRequest request = new IndexRequest("user"); Map<String, Object> jsonMap = new HashMap<>(); jsonMap.put("username", "张三"); jsonMap.put("password", "123456"); request.source(jsonMap); IndexResponse response = client.index(request, RequestOptions.DEFAULT); log.info("添加单条索引的结果是:{}",JSON.toJSONString(response)); }
2)批量插入数据
@Test
public void bulkInsertData() throws Exception {
List<Map<String, Object>> list = new ArrayList<>();
for (int i = 0; i < 100; i++) {
Map<String, Object> jsonMap = new HashMap<>();
jsonMap.put("username", "张三");
jsonMap.put("password", "123456" + i);
list.add(jsonMap);
}
/**
* 批量从插入数据
*/
BulkRequest request = new BulkRequest();
for (int j = 0; j < list.size(); j++) {
Map<String, Object> item = list.get(j);
request.add(new IndexRequest("user").source(item));
}
BulkResponse response = client.bulk(request, RequestOptions.DEFAULT);
log.info("批量添加索引的结果是:{}", JSON.toJSONString(response));
}五、查询
1)查询全部
@Test
public void queryAll() throws Exception {
SearchRequest request = new SearchRequest();
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
log.info("查询全部获取的结果是:{}", JSON.toJSONString(response));
}2)根据id进行查询
@Test
public void getById() throws Exception {
GetRequest request = new GetRequest("user", "z2aNzYEBa29IIbHz8EaE");
GetResponse response = client.get(request, RequestOptions.DEFAULT);
log.info("getById获取的结果是:{}", JSON.toJSONString(response));
}3)根据关键词查询
@Test
public void queryByKeyWord() throws Exception {
SearchRequest request = new SearchRequest("user");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
TermQueryBuilder termQuery = QueryBuilders.termQuery("password", "12345628");
searchSourceBuilder.query(termQuery);
request.source(searchSourceBuilder);
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
log.info("查询全部获取的结果是:{}", JSON.toJSONString(response));
}根据关键词进行搜索的情况,主要是编写querybuilder即可,所以其他的querybuilder就暂时不在这列举了。
六、更新
@Test
public void updateDocumentById() throws Exception {
Map<String, Object> jsonMap = new HashMap<>();
jsonMap.put("username", "李四");
jsonMap.put("password", "111");
UpdateRequest request = new UpdateRequest("user","z2aNzYEBa29IIbHz8EaE").doc(jsonMap);
UpdateResponse response = client.update(request, RequestOptions.DEFAULT);
log.info("updateDocumentById获取的结果是:{}", JSON.toJSONString(response));
}七、删除
1)根据id删除
@Test
public void deleteById() throws Exception {
DeleteRequest request = new DeleteRequest("user","z2aNzYEBa29IIbHz8EaE");
DeleteResponse response = client.delete(request, RequestOptions.DEFAULT);
log.info("deleteById获取的结果是:{}", JSON.toJSONString(response));
}2)根据条件删除
@Test
public void deleteByQuery() throws Exception {
DeleteByQueryRequest request = new DeleteByQueryRequest("user");
request.setQuery(new TermQueryBuilder("password", "12345613"));
// 更新最大文档数
request.setSize(10);
// 批次大小
request.setBatchSize(1000);
// 并行
request.setSlices(2);
// 使用滚动参数来控制“搜索上下文”存活的时间
request.setScroll(TimeValue.timeValueMinutes(10));
// 超时
request.setTimeout(TimeValue.timeValueMinutes(2));
// 刷新索引
request.setRefresh(true);
BulkByScrollResponse response = client.deleteByQuery(request, RequestOptions.DEFAULT);
log.info("deleteById获取的结果是:{}", JSON.toJSONString(response));
}备注
1、对于生产上使用的client初始化的话,我们可以参考下面的工具类:
package com.demo; import org.apache.http.HttpHost; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.impl.client.BasicCredentialsProvider; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestClientBuilder; import org.elasticsearch.client.RestHighLevelClient; /** * 这个工具类主要是用于初始化client,在spring项目中需要使用bean注入即可。 */ public class RestHighLevelClientUtils { // es host ip 地址(集群) private static String hosts = "192.168.31.218:9200"; // es用户名 private static String userName = ""; // es密码 private static String password= ""; // es 请求方式 private static String scheme= ""; // es集群名称 private static String clusterName= ""; // es 连接超时时间 private static int connectTimeOut = 60000; // es socket 连接超时时间 private static int socketTimeOut = 60000; // es 请求超时时间 private static int connectionRequestTimeOut = 60000; // es 最大连接数 private static int maxConnectNum = 1000; // es 每个路由的最大连接数 private static int maxConnectNumPerRoute = 10000; public static RestHighLevelClient newInstance(){ String host = hosts.split(":")[0]; String port = hosts.split(":")[1]; HttpHost httpHost = new HttpHost(host,Integer.parseInt(port)); // 构建连接对象 RestClientBuilder builder = RestClient.builder(httpHost); // 设置用户名、密码 CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY,new UsernamePasswordCredentials(userName,password)); // 连接延时配置 builder.setRequestConfigCallback(requestConfigBuilder -> { requestConfigBuilder.setConnectTimeout(connectTimeOut); requestConfigBuilder.setSocketTimeout(socketTimeOut); requestConfigBuilder.setConnectionRequestTimeout(connectionRequestTimeOut); return requestConfigBuilder; }); // 连接数配置 builder.setHttpClientConfigCallback(httpClientBuilder -> { httpClientBuilder.setMaxConnTotal(maxConnectNum); httpClientBuilder.setMaxConnPerRoute(maxConnectNumPerRoute); httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider); return httpClientBuilder; }); return new RestHighLevelClient(builder); } }

还没有评论,来说两句吧...