Elasticsearch 软件是由Java语言开发的,所以也可以通过JavaAPI的方式对 Elasticsearch服务进行访问。
创建 Maven 项目
我们在 IDEA 开发工具中创建 Maven 项目(模块也可)ES。并修改pom文件,增加Maven依赖关系。
#直接复制在pom文件的<dependencies></dependencies>中
<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>
测试连接客户端,若控制台正常关闭无报错正常连接。
public class ESTest_Client {public static void main(String[] args) throws Exception{//创建ES客户端RestHighLevelClient esClient = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost",9200,"http")));//关闭ES客户端esClient.close();}
}
索引操作
创建索引
public class ESTest_Index_Create {public static void main(String[] args) throws Exception{//创建ES客户端RestHighLevelClient esClient = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost",9200,"http")));//创建索引CreateIndexRequest request = new CreateIndexRequest("user");CreateIndexResponse createIndexResponse = esClient.indices().create(request, RequestOptions.DEFAULT);//响应状态boolean acknowledged = createIndexResponse.isAcknowledged();//索引操作System.out.println("索引操作"+acknowledged);//关闭ES客户端esClient.close();}
}
查询索引
public class ESTest_Index_Search {public static void main(String[] args) throws Exception{//创建ES客户端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.getSettings());//关闭ES客户端esClient.close();}
}
删除索引
public class ESTest_Index_DELETE {public static void main(String[] args) throws Exception{//创建ES客户端RestHighLevelClient esClient = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost",9200,"http")));//删除索引DeleteIndexRequest request = new DeleteIndexRequest("user");AcknowledgedResponse delete = esClient.indices().delete(request, RequestOptions.DEFAULT);//响应状态System.out.println("响应结果"+delete.isAcknowledged());//关闭ES客户端esClient.close();}
}
文档操作
创建User类
public class User {private String name;private int age;private String sex;public User(String name, int age, String sex) {this.name = name;this.age = age;this.sex = sex;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public String getSex() {return sex;}public void setSex(String sex) {this.sex = sex;}
}
新增数据
public class ESTest_Doc_Instert {public static void main(String[] args) throws Exception{//创建ES客户端RestHighLevelClient esClient = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost",9200,"http")));//插入数据IndexRequest request = new IndexRequest();request.index("user").id("1001");User user = new User("zhangsan",30,"nan");//ES插入数据为JSON要将user转成JSONObjectMapper objectMapper = new ObjectMapper();String s = objectMapper.writeValueAsString(user);request.source(s, XContentType.JSON);IndexResponse index = esClient.index(request, RequestOptions.DEFAULT);System.out.println(index.getResult());//关闭ES客户端esClient.close();}
}
修改文档
public class ESTest_Doc_Update {public static void main(String[] args) throws Exception{//创建ES客户端RestHighLevelClient esClient = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost",9200,"http")));//修改数据UpdateRequest request = new UpdateRequest();request.index("user").id("1001");request.doc(XContentType.JSON,"sex","女");UpdateResponse index = esClient.update(request, RequestOptions.DEFAULT);System.out.println(index.getResult());//关闭ES客户端esClient.close();}
}
查询数据
public class ESTest_Doc_Search {public static void main(String[] args) throws Exception{//创建ES客户端RestHighLevelClient esClient = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost",9200,"http")));//查询数据GetRequest getRequest = new GetRequest();getRequest.index("user").id("1001");GetResponse index = esClient.get(getRequest, RequestOptions.DEFAULT);String sourceAsString = index.getSourceAsString();System.out.println(sourceAsString);//关闭ES客户端esClient.close();}
}
文档删除
public class ESTest_Doc_Delete {public static void main(String[] args) throws Exception{//创建ES客户端RestHighLevelClient esClient = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost",9200,"http")));//删除数据DeleteRequest request = new DeleteRequest();request.index("user").id("1001");User user = new User("zhangsan",30,"nan");DeleteResponse index = esClient.delete(request, RequestOptions.DEFAULT);System.out.println(index.getResult());//关闭ES客户端esClient.close();}
}
批量新增
public class ESTest_Doc_Instert_Batch {public static void main(String[] args) throws Exception{//创建ES客户端RestHighLevelClient esClient = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost",9200,"http")));//批量插入数据BulkRequest bulkRequest = new BulkRequest();bulkRequest.add(new IndexRequest().index("user").id("1001").source(XContentType.JSON, "name", "zhangsan"));bulkRequest.add(new IndexRequest().index("user").id("1002").source(XContentType.JSON, "name", "lisi"));bulkRequest.add(new IndexRequest().index("user").id("1002").source(XContentType.JSON, "name", "wangwu"));BulkResponse bulk = esClient.bulk(bulkRequest, RequestOptions.DEFAULT);System.out.println(bulk.getItems());System.out.println(bulk.getItems());//关闭ES客户端esClient.close();}
}
批量删除
public class ESTest_Doc_Delete_Batch {public static void main(String[] args) throws Exception{//创建ES客户端RestHighLevelClient esClient = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost",9200,"http")));//批量删除数据BulkRequest bulkRequest = new BulkRequest();bulkRequest.add(new DeleteRequest().index("user").id("1001"));bulkRequest.add(new DeleteRequest().index("user").id("1002"));bulkRequest.add(new DeleteRequest().index("user").id("1002"));BulkResponse bulk = esClient.bulk(bulkRequest, RequestOptions.DEFAULT);System.out.println(bulk.getItems());System.out.println(bulk.getItems());//关闭ES客户端esClient.close();}
}
高级查询&分页查询
package org.example.ES;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.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.common.unit.Fuzziness;
import org.elasticsearch.index.query.*;
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.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;import javax.naming.directory.SearchResult;
import javax.swing.text.Highlighter;public class ESTest_Doc_Query {public static void main(String[] args) throws Exception{//创建ES客户端RestHighLevelClient esClient = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost",9200,"http")));// //1.查询索引中全量数据
// SearchRequest searchRequest = new SearchRequest();
// searchRequest.indices("user");
//
// searchRequest.source(new SearchSourceBuilder().query(QueryBuilders.matchAllQuery()));
// SearchResponse response = esClient.search(searchRequest, RequestOptions.DEFAULT);
//
// SearchHits hits = response.getHits();
// System.out.println(hits.getTotalHits()+" "+ response.getTook());
// for (SearchHit hit : hits){
//
// System.out.println(hit.getSourceAsString());
// }// //条件查询 :termQuery
// SearchRequest searchRequest = new SearchRequest();
// searchRequest.indices("user");
//
// searchRequest.source(new SearchSourceBuilder().query(QueryBuilders.termQuery("age",30)));
// SearchResponse response = esClient.search(searchRequest, RequestOptions.DEFAULT);
//
// SearchHits hits = response.getHits();
// System.out.println(hits.getTotalHits()+" "+ response.getTook());
// for (SearchHit hit : hits){
//
// System.out.println(hit.getSourceAsString());
// }//分页查询
// SearchRequest searchRequest = new SearchRequest();
// searchRequest.indices("user");
//
// SearchSourceBuilder query = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
// query.from(0);
// query.size(2);
//
// searchRequest.source(query);
// SearchResponse response = esClient.search(searchRequest, RequestOptions.DEFAULT);
//
// SearchHits hits = response.getHits();
// System.out.println(hits.getTotalHits()+" "+ response.getTook());
// for (SearchHit hit : hits){
//
// System.out.println(hit.getSourceAsString());
// }//查询排序
// SearchRequest searchRequest = new SearchRequest();
// searchRequest.indices("user");
//
// SearchSourceBuilder query = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
// query.sort("age", SortOrder.DESC);
//
// searchRequest.source(query);
// SearchResponse response = esClient.search(searchRequest, RequestOptions.DEFAULT);
//
// SearchHits hits = response.getHits();
// System.out.println(hits.getTotalHits()+" "+ response.getTook());
// for (SearchHit hit : hits){
//
// System.out.println(hit.getSourceAsString());
// }//过滤字段
// SearchRequest searchRequest = new SearchRequest();
// searchRequest.indices("user");
//
// SearchSourceBuilder query = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
//
// //排除
// String [] excludes = {"age"};
// //只查询name
// String [] includes = {};
// query.fetchSource(includes,excludes);
//
// searchRequest.source(query);
// SearchResponse response = esClient.search(searchRequest, RequestOptions.DEFAULT);
//
// SearchHits hits = response.getHits();
// System.out.println(hits.getTotalHits()+" "+ response.getTook());
// for (SearchHit hit : hits){
//
// System.out.println(hit.getSourceAsString());
// }//组合查询
// SearchRequest searchRequest = new SearchRequest();
// searchRequest.indices("user");
//
// SearchSourceBuilder query = new SearchSourceBuilder();
// BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
//
// boolQueryBuilder.must(QueryBuilders.matchQuery("age",30));
// boolQueryBuilder.must(QueryBuilders.matchQuery("sex","男"));
//
//
//
// query.query(boolQueryBuilder);
//
// searchRequest.source(query);
// SearchResponse response = esClient.search(searchRequest, RequestOptions.DEFAULT);
//
// SearchHits hits = response.getHits();
// System.out.println(hits.getTotalHits()+" "+ response.getTook());
// for (SearchHit hit : hits){
//
// System.out.println(hit.getSourceAsString());
// }//范围查询
// SearchRequest searchRequest = new SearchRequest();
// searchRequest.indices("user");
//
// SearchSourceBuilder query = new SearchSourceBuilder();
// RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("age");
//
// rangeQuery.gte(30);
// rangeQuery.lte(40);
//
// query.query(rangeQuery);
//
// searchRequest.source(query);
// SearchResponse response = esClient.search(searchRequest, RequestOptions.DEFAULT);
//
// SearchHits hits = response.getHits();
// System.out.println(hits.getTotalHits()+" "+ response.getTook());
// for (SearchHit hit : hits){
//
// System.out.println(hit.getSourceAsString());
// }//模糊查询
////高亮查询
// SearchRequest searchRequest = new SearchRequest();
// searchRequest.indices("user");
//
// SearchSourceBuilder query = new SearchSourceBuilder();
//
// TermsQueryBuilder termsQueryBuilder = QueryBuilders.termsQuery("name", "zhangsan");
//
// HighlightBuilder highlightBuilder = new HighlightBuilder();
// highlightBuilder.preTags("<font> color = 'red'");
// highlightBuilder.postTags("</font>");
// highlightBuilder.field("name");
//
// query.highlighter(highlightBuilder);
// query.query(termsQueryBuilder);
//
// searchRequest.source(query);
// SearchResponse response = esClient.search(searchRequest, RequestOptions.DEFAULT);
//
// SearchHits hits = response.getHits();
// System.out.println(hits.getTotalHits()+" "+ response.getTook());
// for (SearchHit hit : hits){
//
// System.out.println(hit.getSourceAsString());
// }//聚合查询
// SearchRequest searchRequest = new SearchRequest();
// searchRequest.indices("user");
//
// SearchSourceBuilder query = new SearchSourceBuilder();
//
// AggregationBuilder aggregationBuilder = AggregationBuilders.max("maxAge").field("age");
//
// query.aggregation(aggregationBuilder);
//
// query.query();
//
// searchRequest.source(query);
// SearchResponse response = esClient.search(searchRequest, RequestOptions.DEFAULT);
//
// SearchHits hits = response.getHits();
// System.out.println(hits.getTotalHits()+" "+ response.getTook());
// for (SearchHit hit : hits){
//
// System.out.println(hit.getSourceAsString());
// }//分组查询SearchRequest searchRequest = new SearchRequest();searchRequest.indices("user");SearchSourceBuilder query = new SearchSourceBuilder();AggregationBuilder aggregationBuilder = AggregationBuilders.terms("ageGrroup").field("age");query.aggregation(aggregationBuilder);query.query();searchRequest.source(query);SearchResponse response = esClient.search(searchRequest, RequestOptions.DEFAULT);SearchHits hits = response.getHits();System.out.println(hits.getTotalHits()+" "+ response.getTook());for (SearchHit hit : hits){System.out.println(hit.getSourceAsString());}//关闭ES客户端esClient.close();}
}
全量查询
条件查询
分页查询
排序查询
只查姓名
排除年龄
多条件查询
范围查询
模糊查询