前言
Elasticsearch 软件是由 Java 语言开发的,所以也可以通过 JavaAPI 的方式对 Elasticsearch 服务进行访问 之前是对ES中的创建/查看/删除索引、创建定义映射、创建/查看/修改/删除文档的这些操作有了一定的了解认识,但是是通过Postman + JSON串的方法来实现的
那么之后仍然是对ES中的索引、映射、文档进行操作,只是方法换成了Java API。
一:导包
<dependencies>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>7.8.0</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.8.0</version>
</dependency>
<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>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
</dependencies>
二:客户端对象
创建 com.atguigu.es.test.Elasticsearch01_Client 类,代码中创建 Elasticsearch 客户端对象 因为早期版本的客户端对象已经不再推荐使用,且在未来版本中会被删除,所以这里我们采 用高级 REST 客户端对象-RestHighLevelClient
package es;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import java.io.IOException;
public class EsClient {
public static void main(String[] args) throws IOException {
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
esClient.close();
}
}
三:客户端操作
1:索引操作
1:创建索引
public class CreateIndex {
public static void main(String[] args) throws IOException {
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
CreateIndexRequest createIndexRequest = new CreateIndexRequest("user");
CreateIndexResponse createIndexResponse = esClient.indices().create(createIndexRequest, RequestOptions.DEFAULT);
boolean acknowledged = createIndexResponse.isAcknowledged();
System.out.println("索引操作:"+acknowledged);
esClient.close();
}
}
2:查看索引
public class GerIndex {
public static void main(String[] args) throws IOException {
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
GetIndexRequest request = new GetIndexRequest("user");
GetIndexResponse getIndexResponse = esClient.indices().get(request, RequestOptions.DEFAULT);
System.out.println(getIndexResponse.getAliases());
System.out.println(getIndexResponse.getMappings());
System.out.println(getIndexResponse.getDataStreams());
System.out.println(getIndexResponse.getSettings());
esClient.close();
}
}
3:删除索引
public class DeleteIndex {
public static void main(String[] args) throws IOException {
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest("student");
AcknowledgedResponse delete = esClient.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
System.out.println(delete.isAcknowledged());
esClient.close();
}
}
2:文档操作
1:创建文档
1:创建实体-我这里使用了lombok代替get,set,这个就不介绍了哈 /**
- @author wkl
- @create 2022-06-28 15:24
*/ @Data public class User { private String name; private String sex; private int age; } 2:创建文档
public class CreateDocument {
public static void main(String[] args) throws IOException {
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
IndexRequest indexRequest = new IndexRequest();
indexRequest.index("user").id("1");
User user = new User();
user.setName("张三");
user.setSex("男");
user.setAge(35);
user.setBir(new Date());
indexRequest.source(JSONObject.toJSONString(user), XContentType.JSON);
IndexResponse index = esClient.index(indexRequest, RequestOptions.DEFAULT);
System.out.println(index.getId());
System.out.println(index.getIndex());
System.out.println(index.getResult());
esClient.close();
}
}
2:查询文档
public class UpdateDocument {
public static void main(String[] args) throws IOException {
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
UpdateRequest updateRequest = new UpdateRequest();
updateRequest.index("user").id("1");
updateRequest.doc(XContentType.JSON,"age",26);
UpdateResponse update = esClient.update(updateRequest, RequestOptions.DEFAULT);
System.out.println(update.getResult());
esClient.close();
}
}
3:删除文档
public class DeleteDoucument {
public static void main(String[] args) throws IOException {
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
DeleteRequest deleteRequest = new DeleteRequest();
deleteRequest.index("user").id("1");
DeleteResponse delete = esClient.delete(deleteRequest, RequestOptions.DEFAULT);
System.out.println(delete.getResult());
esClient.close();
}
}
4:批量新增
public class BatchCreateDocument {
public static void main(String[] args) throws IOException {
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
BulkRequest bulkRequest = new BulkRequest();
bulkRequest.add(new IndexRequest().index("user").id("2").source(JSONObject.toJSONString(new User("李四","男",20,new Date())), XContentType.JSON));
bulkRequest.add(new IndexRequest().index("user").id("3").source(JSONObject.toJSONString(new User("小花","女",18,new Date())), XContentType.JSON));
bulkRequest.add(new IndexRequest().index("user").id("4").source(JSONObject.toJSONString(new User("小雪","女",24,new Date())), XContentType.JSON));
BulkResponse bulk = esClient.bulk(bulkRequest, RequestOptions.DEFAULT);
System.out.println(bulk.getTook());
esClient.close();
}
}
5:批量删除
public class BatchDleteDocument {
public static void main(String[] args) throws IOException {
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
BulkRequest bulkRequest = new BulkRequest();
bulkRequest.add(new DeleteRequest().index("user").id("1"));
bulkRequest.add(new DeleteRequest().index("user").id("2"));
BulkResponse bulk = esClient.bulk(bulkRequest, RequestOptions.DEFAULT);
System.out.println(bulk.getItems());
esClient.close();
}
}
3:高级查询
1:全量查询
public class Match_allQuery {
public static void main(String[] args) throws IOException {
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
SearchRequest searchRequest = new SearchRequest();
searchRequest.indices("user");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.matchAllQuery());
searchRequest.source(searchSourceBuilder);
SearchResponse search = esClient.search(searchRequest, RequestOptions.DEFAULT);
SearchHits hits = search.getHits();
for (SearchHit hit : hits) {
System.out.println(hit.getSourceAsString());
}
esClient.close();
}
}
2:条件查询-term 查询,查询条件为关键字
public class TermQuery {
public static void main(String[] args) throws IOException {
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
SearchRequest searchRequest = new SearchRequest();
searchRequest.indices("user");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.termQuery("age",20));
searchRequest.source(searchSourceBuilder);
SearchResponse search = esClient.search(searchRequest, RequestOptions.DEFAULT);
SearchHits hits = search.getHits();
for (SearchHit hit : hits) {
System.out.println(hit.getSourceAsString());
}
esClient.close();
}
}
3:分词查询-match
public class MatchQuery {
public static void main(String[] args) throws IOException {
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
SearchRequest searchRequest = new SearchRequest();
searchRequest.indices("user");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.matchQuery("name","小"));
searchRequest.source(searchSourceBuilder);
SearchResponse search = esClient.search(searchRequest, RequestOptions.DEFAULT);
SearchHits hits = search.getHits();
for (SearchHit hit : hits) {
System.out.println(hit.getSourceAsString());
}
esClient.close();
}
}
4:分页查询-from&size
public class MatchOfpageQuery {
public static void main(String[] args) throws IOException {
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
SearchRequest searchRequest = new SearchRequest();
searchRequest.indices("user");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.matchAllQuery());
searchSourceBuilder.from(0);
searchSourceBuilder.size(2);
searchRequest.source(searchSourceBuilder);
SearchResponse search = esClient.search(searchRequest, RequestOptions.DEFAULT);
SearchHits hits = search.getHits();
for (SearchHit hit : hits) {
System.out.println(hit.getSourceAsString());
}
esClient.close();
}
}
5:数据排序-sort
public class SortQuery {
public static void main(String[] args) throws IOException {
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
SearchRequest searchRequest = new SearchRequest();
searchRequest.indices("user");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.matchAllQuery());
searchSourceBuilder.sort("age", SortOrder.DESC);
searchRequest.source(searchSourceBuilder);
SearchResponse search = esClient.search(searchRequest, RequestOptions.DEFAULT);
SearchHits hits = search.getHits();
for (SearchHit hit : hits) {
System.out.println(hit.getSourceAsString());
}
esClient.close();
}
}
6:过滤字段-fetch
public class FilterQuery {
public static void main(String[] args) throws IOException {
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
SearchRequest searchRequest = new SearchRequest();
searchRequest.indices("user");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.matchAllQuery());
String[] excludes = {};
String[] includes = {"age","sex"};
searchSourceBuilder.fetchSource(includes,excludes);
searchRequest.source(searchSourceBuilder);
SearchResponse search = esClient.search(searchRequest, RequestOptions.DEFAULT);
SearchHits hits = search.getHits();
for (SearchHit hit : hits) {
System.out.println(hit.getSourceAsString());
}
esClient.close();
}
}
7:Bool查询-bool
public class BoolQuery {
public static void main(String[] args) throws IOException {
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
SearchRequest searchRequest = new SearchRequest();
searchRequest.indices("user");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
boolQueryBuilder.must (QueryBuilders.matchQuery("age", "18"));
boolQueryBuilder.mustNot (QueryBuilders.matchQuery("name", "zhangsan"));
boolQueryBuilder.should (QueryBuilders.matchQuery("sex", "女"));
searchSourceBuilder.query(boolQueryBuilder);
searchRequest.source(searchSourceBuilder);
SearchResponse search = esClient.search(searchRequest, RequestOptions.DEFAULT);
SearchHits hits = search.getHits();
for (SearchHit hit : hits) {
System.out.println(hit.getSourceAsString());
}
esClient.close();
}
}
8:范围查询-range
public class RangQuery {
public static void main(String[] args) throws IOException {
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
SearchRequest searchRequest = new SearchRequest();
searchRequest.indices("user");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
RangeQueryBuilder rangeQueryBuilder = new RangeQueryBuilder("age");
rangeQueryBuilder.gte(18);
rangeQueryBuilder.lte(30);
searchSourceBuilder.query(rangeQueryBuilder);
searchRequest.source(searchSourceBuilder);
SearchResponse search = esClient.search(searchRequest, RequestOptions.DEFAULT);
SearchHits hits = search.getHits();
for (SearchHit hit : hits) {
System.out.println(hit.getSourceAsString());
}
esClient.close();
}
}
9:模糊查询-fuzzi
public class FuzzinQuery {
public static void main(String[] args) throws IOException {
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
SearchRequest searchRequest = new SearchRequest();
searchRequest.indices("user");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
FuzzyQueryBuilder fuzzyQueryBuilder = QueryBuilders.fuzzyQuery("name", "小");
searchSourceBuilder.query(fuzzyQueryBuilder.fuzziness(Fuzziness.ONE));
searchRequest.source(searchSourceBuilder);
SearchResponse search = esClient.search(searchRequest, RequestOptions.DEFAULT);
SearchHits hits = search.getHits();
for (SearchHit hit : hits) {
System.out.println(hit.getSourceAsString());
}
esClient.close();
}
}
10:聚合查询
public class AggrQuery {
public static void main(String[] args) throws IOException {
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
SearchRequest searchRequest = new SearchRequest();
searchRequest.indices("user");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.aggregation(AggregationBuilders.max("max_value").field("age"));
searchRequest.source(searchSourceBuilder);
SearchResponse search = esClient.search(searchRequest, RequestOptions.DEFAULT);
SearchHits hits = search.getHits();
for (SearchHit hit : hits) {
System.out.println(hit.getSourceAsString());
}
esClient.close();
}
}
11:分组查询
public class AggrGroupQuery {
public static void main(String[] args) throws IOException {
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
SearchRequest searchRequest = new SearchRequest();
searchRequest.indices("user");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.aggregation(AggregationBuilders.terms("group_value").field("age"));
searchRequest.source(searchSourceBuilder);
SearchResponse search = esClient.search(searchRequest, RequestOptions.DEFAULT);
SearchHits hits = search.getHits();
for (SearchHit hit : hits) {
System.out.println(hit.getSourceAsString());
}
esClient.close();
}
}
四:springboot中使用HighLevelClient 操作es
上述利用的是javase程序来进行测试的,但是我们现在环境基本都是springboot,实际上springboot环境下使用和上边是一样的,就是client客户端采用依赖注入的方式;
1:导包
<dependencies>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>7.8.0</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.8.0</version>
</dependency>
<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>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
</dependencies>
2:配置config,链接es
package es.config;
import java.util.ArrayList;
import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig.Builder;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestClientBuilder.HttpClientConfigCallback;
import org.elasticsearch.client.RestClientBuilder.RequestConfigCallback;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class EsConfiguration {
private static String hosts = "192.168.62.145";
private static int port = 9200;
private static String schema = "http";
private static ArrayList<HttpHost> hostList = null;
private static int connectTimeOut = 1000;
private static int socketTimeOut = 30000;
private static int connectionRequestTimeOut = 500;
private static int maxConnectNum = 100;
private static int maxConnectPerRoute = 100;
private RestClientBuilder builder;
static {
hostList = new ArrayList<>();
String[] hostStrs = hosts.split(",");
for (String host : hostStrs) {
hostList.add(new HttpHost(host, port, schema));
}
}
@Bean
public RestHighLevelClient client() {
builder = RestClient.builder(hostList.toArray(new HttpHost[0]));
setConnectTimeOutConfig();
setMutiConnectConfig();
RestHighLevelClient client = new RestHighLevelClient(builder);
return client;
}
public void setConnectTimeOutConfig() {
builder.setRequestConfigCallback(new RequestConfigCallback() {
@Override
public Builder customizeRequestConfig(Builder requestConfigBuilder) {
requestConfigBuilder.setConnectTimeout(connectTimeOut);
requestConfigBuilder.setSocketTimeout(socketTimeOut);
requestConfigBuilder.setConnectionRequestTimeout(connectionRequestTimeOut);
return requestConfigBuilder;
}
});
}
public void setMutiConnectConfig() {
builder.setHttpClientConfigCallback(new HttpClientConfigCallback() {
@Override
public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
httpClientBuilder.setMaxConnTotal(maxConnectNum);
httpClientBuilder.setMaxConnPerRoute(maxConnectPerRoute);
return httpClientBuilder;
}
});
}
}
3:依赖注入使用
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.RestHighLevelClient;
import java.io.IOException;
public class Test {
@Autowired
private RestHighLevelClient client;
@Test
public void createIndex() throws IOException {
CreateIndexRequest request = new CreateIndexRequest("六脉神剑");
CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT);
System.out.println("createIndex: " + JSON.toJSONString(createIndexResponse));
}
}
|