导入Java与ElasticSerach的依赖
<dependency>
<groupId>org.elasticsearchgroupId>
<artifactId>elasticsearchartifactId>
<version>7.9.3version>
dependency>
<dependency>
<groupId>org.elasticsearch.clientgroupId>
<artifactId>elasticsearch-rest-high-level-clientartifactId>
<version>7.9.3version>
dependency>
<dependency>
<groupId>org.apache.logging.log4jgroupId>
<artifactId>log4j-apiartifactId>
<version>2.8.2version>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-databindartifactId>
<version>2.12.5version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>fastjsonartifactId>
<version>1.2.75version>
dependency>
编写测试类,尝试获取ES连接
public class ESTestClient {
public static void main(String[] args) throws Exception {
//创建es客户端
RestHighLevelClient esClient = new RestHighLevelClient(RestClient.builder(new HttpHost("127.0.0.1", 9200)));
System.out.println(esClient);
//关闭客户端连接
esClient.close();
}
}
public class ESTestIndexCreate {
public static void main(String[] args) throws Exception {
//创建es客户端
RestHighLevelClient esClient = new RestHighLevelClient(RestClient.builder(new HttpHost("127.0.0.1", 9200)));
System.out.println(esClient);
//创建索引
CreateIndexRequest request = new CreateIndexRequest("user");
CreateIndexResponse createIndexResponse = esClient.indices().create(request, RequestOptions.DEFAULT);
//拿到响应状态
boolean acknowledged = createIndexResponse.isAcknowledged();
System.out.println("索引操作: "+ acknowledged);
//关闭客户端连接
esClient.close();
}
}
public class ESTestGetIndex {
public static void main(String[] args) throws Exception {
//创建es客户端
RestHighLevelClient esClient = new RestHighLevelClient(RestClient.builder(new HttpHost("127.0.0.1", 9200)));
System.out.println(esClient);
//创建索引连接
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());
//关闭客户端连接
esClient.close();
}
}
public class ESTestIndexDelete {
public static void main(String[] args) throws Exception {
//创建es客户端
RestHighLevelClient esClient = new RestHighLevelClient(RestClient.builder(new HttpHost("127.0.0.1", 9200)));
System.out.println(esClient);
//删除索引
DeleteIndexRequest request = new DeleteIndexRequest("user2");
AcknowledgedResponse delete = esClient.indices().delete(request, RequestOptions.DEFAULT);
//拿到响应状态
boolean acknowledged = delete.isAcknowledged();
System.out.println("索引删除操作: "+ acknowledged);
//关闭客户端连接
esClient.close();
}
}
创建一个实体类User,用来和es中user索引数据匹配
@Data
public class User {
private String name;
private String sex;
private String tel;
private Integer age;
public static User createRandUser(int i){
User user = new User();
user.setTel("手机"+i);
user.setSex("性别"+i);
user.setName("zhangsan"+i);
user.setAge(30+i-1);
return user;
}
}
public class ESTestDocInsert {
public static void main(String[] args) throws Exception {
//创建es客户端
RestHighLevelClient esClient = new RestHighLevelClient(RestClient.builder(new HttpHost("127.0.0.1", 9200)));
System.out.println(esClient);
IndexRequest request = new IndexRequest();
//方式1 这种方式会根据id 将数据进行新增 ,如果存在相同id,则会整体覆盖
//request.index("user").id("1004");
//不指定id的情况,es会自己生成一个随机串变成id
request.index("user");
//构建对象
User user = new User();
user.setName("zhangsan22");
user.setSex("男性");
user.setTel("1111");
//向es插入数据,必须将数据转成json格式
ObjectMapper mapper = new ObjectMapper();
String userJson = mapper.writeValueAsString(user);
request.source(userJson, XContentType.JSON);
IndexResponse response = esClient.index(request, RequestOptions.DEFAULT);
System.out.println(response.getResult());
//关闭客户端连接
esClient.close();
}
}
/**
* 根据id数组批量删除
*/
public class ESTestDocInsertBulk {
public static void main(String[] args) throws Exception {
//创建es客户端
RestHighLevelClient esClient = new RestHighLevelClient(RestClient.builder(new HttpHost("127.0.0.1", 9200)));
System.out.println(esClient);
//创建请求头
BulkRequest request = new BulkRequest("user");
List<String> idList = Arrays.asList("1,2,3,4".split(","));
int i = 1;
ObjectMapper mapper = new ObjectMapper();
for (String id : idList) {
User user = User.createRandUser(i);
String userJson = mapper.writeValueAsString(user);
request.add(new IndexRequest().index("user").id(id).source(userJson, XContentType.JSON));
i++;
}
BulkResponse response = esClient.bulk(request, RequestOptions.DEFAULT);
System.out.println(response.getTook());
System.out.println(response.getItems());
//关闭客户端连接
esClient.close();
}
}
/**
* 直接根据id删除
*/
public class ESTestDocDeleteById {
public static void main(String[] args) throws Exception {
//创建es客户端
RestHighLevelClient esClient = new RestHighLevelClient(RestClient.builder(new HttpHost("127.0.0.1", 9200)));
System.out.println(esClient);
//构建删除请求
DeleteRequest request = new DeleteRequest("user");
request.id("1003");
DeleteResponse response = esClient.delete(request, RequestOptions.DEFAULT);
System.out.println(response.getResult());
//关闭客户端连接
esClient.close();
}
}
/**
* 根据id数组批量删除
*/
public class ESTestDocDeleteBulk {
public static void main(String[] args) throws Exception {
//创建es客户端
RestHighLevelClient esClient = new RestHighLevelClient(RestClient.builder(new HttpHost("127.0.0.1", 9200)));
System.out.println(esClient);
BulkRequest request = new BulkRequest("user");
List<String> idList = Arrays.asList("1,2,3,4".split(","));
for (String id : idList) {
request.add(new DeleteRequest().index("user").id(id));
}
BulkResponse response = esClient.bulk(request, RequestOptions.DEFAULT);
System.out.println(response.getTook());
System.out.println(response.getItems());
//关闭客户端连接
esClient.close();
}
}
这里说的是部分修改,整体覆盖修改参考带id新增
/**
* 直接根据id部分修改
*/
public class ESTestDocUpdate {
public static void main(String[] args) throws Exception {
//创建es客户端
RestHighLevelClient esClient = new RestHighLevelClient(RestClient.builder(new HttpHost("127.0.0.1", 9200)));
System.out.println(esClient);
//修改数据 部分修改
UpdateRequest request = new UpdateRequest();
request.index("user").id("1003");
//字段 修改后值
request.doc(XContentType.JSON,"age","23","sex","男性");
UpdateResponse response = esClient.update(request, RequestOptions.DEFAULT);
System.out.println(response.getResult());
//关闭客户端连接
esClient.close();
}
}
/**
* 直接根据id查找
*/
public class ESTestDocQueryById {
public static void main(String[] args) throws Exception {
//创建es客户端
RestHighLevelClient esClient = new RestHighLevelClient(RestClient.builder(new HttpHost("127.0.0.1", 9200)));
System.out.println(esClient);
//查询数据
GetRequest request = new GetRequest("user");
request.id("_Ee4D4IBS68PlTMezCd0");
GetResponse response = esClient.get(request, RequestOptions.DEFAULT);
System.out.println(response.getSourceAsString());
User user = JSON.parseObject(response.getSourceAsString(), User.class);
System.out.println(user.toString());
//关闭客户端连接
esClient.close();
}
}
private static void queryALl(RestHighLevelClient esClient)throws Exception {
//查询索引中的全部数据
SearchRequest request = new SearchRequest();
request.indices("user");
//查询全部 matchAll
request.source(new SearchSourceBuilder().query(QueryBuilders.matchAllQuery()));
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
System.out.println(hits.getTotalHits());
System.out.println(response.getTook());
for (SearchHit hit : hits.getHits()) {
System.out.println(hit.getSourceAsString());
}
}
private static void queryCondition(RestHighLevelClient esClient) throws Exception {
//查询索引中的全部数据
SearchRequest request = new SearchRequest();
request.indices("user");
//分词中 同时包含李强才可以,因为底层默认使用英文分词器,所以李强会被分为 李,强没办法符合条件所以查询不到
//request.source(new SearchSourceBuilder().query(QueryBuilders.termQuery("name","李强")));
//这样是李强字段不可再分,查询name字段中包含此字段的数据
request.source(new SearchSourceBuilder().query(QueryBuilders.matchPhraseQuery ("name","李强")));
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
System.out.println(hits.getTotalHits());
System.out.println(response.getTook());
for (SearchHit hit : hits.getHits()) {
System.out.println(hit.getSourceAsString());
}
}
private static void queryPage(RestHighLevelClient esClient) throws Exception {
SearchRequest request = new SearchRequest();
request.indices("user");
//构造查询条件
SearchSourceBuilder query = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
//分页
query.from(0); //从第几条数据开始截取 (页码-1)* 每页数量
query.size(2); //每页的数量
String[] excludes = {"name"}; //排除字段
String[] includes = {"tel"}; //展示字段
query.fetchSource(includes,excludes);
//排序
query.sort("tel",SortOrder.ASC);
request.source(query);
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
for (SearchHit hit : hits.getHits()) {
System.out.println(hit.getSourceAsString());
}
}
private static void queryConditionS(RestHighLevelClient esClient)throws Exception {
SearchRequest request = new SearchRequest();
request.indices("user");
//构造查询条件
SearchSourceBuilder builder = new SearchSourceBuilder();
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
//组合条件查询
//与
// boolQueryBuilder.must(QueryBuilders.matchQuery("name","小"));
// boolQueryBuilder.must(QueryBuilders.matchQuery("sex","性别1"));
// boolQueryBuilder.mustNot(QueryBuilders.matchQuery("sex","性别1"));
//或
boolQueryBuilder.should(QueryBuilders.matchQuery("name","华"));
boolQueryBuilder.should(QueryBuilders.matchQuery("sex","男"));
//排序
builder.sort("tel",SortOrder.ASC);
builder.query(boolQueryBuilder);
request.source(builder);
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
System.out.println(hits.getTotalHits());
System.out.println(response.getTook());
for (SearchHit hit : hits.getHits()) {
System.out.println(hit.getSourceAsString());
}
}
4.6 范围查询
private static void queryBetween(RestHighLevelClient esClient) throws Exception{
SearchRequest request = new SearchRequest();
request.indices("user");
//构造查询条件
SearchSourceBuilder builder = new SearchSourceBuilder();
RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("age");
rangeQueryBuilder.gte(30);
rangeQueryBuilder.lte(32);
//排序
builder.sort("tel",SortOrder.ASC);
builder.query(rangeQueryBuilder);
request.source(builder);
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
System.out.println(hits.getTotalHits());
System.out.println(response.getTook());
for (SearchHit hit : hits.getHits()) {
System.out.println(hit.getSourceAsString());
}
}
private static void queryLike(RestHighLevelClient esClient) throws Exception{
SearchRequest request = new SearchRequest();
request.indices("user");
//构造查询条件
SearchSourceBuilder builder = new SearchSourceBuilder();
builder.query(QueryBuilders.fuzzyQuery("name","zhangsan").fuzziness(Fuzziness.ONE));
request.source(builder);
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
System.out.println(hits.getTotalHits());
System.out.println(response.getTook());
for (SearchHit hit : hits.getHits()) {
System.out.println(hit.getSourceAsString());
}
}
private static void queryHighLighter(RestHighLevelClient esClient) throws Exception{
SearchRequest request = new SearchRequest();
request.indices("user");
//构造查询条件
SearchSourceBuilder builder = new SearchSourceBuilder();
TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "zhang");
HighlightBuilder highlightBuilder = new HighlightBuilder();
highlightBuilder.preTags(""
);
highlightBuilder.postTags("");
highlightBuilder.field("name");
builder.highlighter(highlightBuilder);
builder.query(termQueryBuilder);
request.source(builder);
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
System.out.println(hits.getTotalHits());
System.out.println(response.getTook());
for (SearchHit hit : hits.getHits()) {
System.out.println(hit.getSourceAsString());
}
}
private static void queryAggregation(RestHighLevelClient esClient)throws Exception {
SearchRequest request = new SearchRequest();
request.indices("user");
//构造查询条件
SearchSourceBuilder builder = new SearchSourceBuilder();
//分组名称,聚合字段
AggregationBuilder aggregationBuilder= AggregationBuilders.max("maxAge").field("age");
builder.aggregation(aggregationBuilder);
request.source(builder);
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
System.out.println( response);
SearchHits hits = response.getHits();
System.out.println(hits.getTotalHits());
System.out.println(response.getTook());
for (SearchHit hit : hits.getHits()) {
System.out.println(hit.getSourceAsString());
}
}
private static void queryGroup(RestHighLevelClient esClient) throws Exception {
SearchRequest request = new SearchRequest();
request.indices("user");
//构造查询条件
SearchSourceBuilder builder = new SearchSourceBuilder();
AggregationBuilder aggregationBuilder= AggregationBuilders.terms("ageGroup").field("age");
builder.aggregation(aggregationBuilder);
request.source(builder);
SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
System.out.println( response);
SearchHits hits = response.getHits();
System.out.println(hits.getTotalHits());
System.out.println(response.getTook());
for (SearchHit hit : hits.getHits()) {
System.out.println(hit.getSourceAsString());
}
}