0


ElasticSearch(四)Java中使用ES

Java内使用ES

文章目录


1、JAVA整合ElasticSearch

  1. 导入Java与ElasticSerach的依赖<!--ES--><dependency><groupId>org.elasticsearch</groupId><artifactId>elasticsearch</artifactId><version>7.9.3</version></dependency><!--es客户端--><dependency><groupId>org.elasticsearch.client</groupId><artifactId>elasticsearch-rest-high-level-client</artifactId><version>7.9.3</version></dependency><!--处理es日志--><dependency><groupId>org.apache.logging.log4j</groupId><artifactId>log4j-api</artifactId><version>2.8.2</version></dependency><!--json转换--><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.12.5</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.75</version></dependency>
  2. 编写测试类,尝试获取ES连接publicclassESTestClient{publicstaticvoidmain(String[] args)throwsException{//创建es客户端RestHighLevelClient esClient =newRestHighLevelClient(RestClient.builder(newHttpHost("127.0.0.1",9200)));System.out.println(esClient);//关闭客户端连接 esClient.close();}}

2、JAVA内操作索引

2.1 创建索引

publicclassESTestIndexCreate{publicstaticvoidmain(String[] args)throwsException{//创建es客户端RestHighLevelClient esClient =newRestHighLevelClient(RestClient.builder(newHttpHost("127.0.0.1",9200)));System.out.println(esClient);//创建索引CreateIndexRequest request =newCreateIndexRequest("user");CreateIndexResponse createIndexResponse = esClient.indices().create(request,RequestOptions.DEFAULT);//拿到响应状态boolean acknowledged = createIndexResponse.isAcknowledged();System.out.println("索引操作: "+ acknowledged);//关闭客户端连接
        esClient.close();}}

2.2 获取索引信息

publicclassESTestGetIndex{publicstaticvoidmain(String[] args)throwsException{//创建es客户端RestHighLevelClient esClient =newRestHighLevelClient(RestClient.builder(newHttpHost("127.0.0.1",9200)));System.out.println(esClient);//创建索引连接GetIndexRequest request =newGetIndexRequest("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();}}

2.3 删除索引信息

publicclassESTestIndexDelete{publicstaticvoidmain(String[] args)throwsException{//创建es客户端RestHighLevelClient esClient =newRestHighLevelClient(RestClient.builder(newHttpHost("127.0.0.1",9200)));System.out.println(esClient);//删除索引DeleteIndexRequest request =newDeleteIndexRequest("user2");AcknowledgedResponse delete = esClient.indices().delete(request,RequestOptions.DEFAULT);//拿到响应状态boolean acknowledged = delete.isAcknowledged();System.out.println("索引删除操作: "+ acknowledged);//关闭客户端连接
        esClient.close();}}

3、JAVA内增删改doc

创建一个实体类User,用来和es中user索引数据匹配

@DatapublicclassUser{privateString name;privateString sex;privateString tel;privateInteger age;publicstaticUsercreateRandUser(int i){User user =newUser();
        user.setTel("手机"+i);
        user.setSex("性别"+i);
        user.setName("zhangsan"+i);
        user.setAge(30+i-1);return user;}}

3.1 新增文档信息

publicclassESTestDocInsert{publicstaticvoidmain(String[] args)throwsException{//创建es客户端RestHighLevelClient esClient =newRestHighLevelClient(RestClient.builder(newHttpHost("127.0.0.1",9200)));System.out.println(esClient);IndexRequest request =newIndexRequest();//方式1 这种方式会根据id 将数据进行新增 ,如果存在相同id,则会整体覆盖//request.index("user").id("1004");//不指定id的情况,es会自己生成一个随机串变成id
        request.index("user");//构建对象User user =newUser();
        user.setName("zhangsan22");
        user.setSex("男性");
        user.setTel("1111");//向es插入数据,必须将数据转成json格式ObjectMapper mapper =newObjectMapper();String userJson = mapper.writeValueAsString(user);
        request.source(userJson,XContentType.JSON);IndexResponse response = esClient.index(request,RequestOptions.DEFAULT);System.out.println(response.getResult());//关闭客户端连接
        esClient.close();}}

3.2 批量新增文档信息

/**
 * 根据id数组批量删除
 */publicclassESTestDocInsertBulk{publicstaticvoidmain(String[] args)throwsException{//创建es客户端RestHighLevelClient esClient =newRestHighLevelClient(RestClient.builder(newHttpHost("127.0.0.1",9200)));System.out.println(esClient);//创建请求头BulkRequest request =newBulkRequest("user");List<String> idList  =Arrays.asList("1,2,3,4".split(","));int i =1;ObjectMapper mapper =newObjectMapper();for(String id : idList){User user =User.createRandUser(i);String userJson = mapper.writeValueAsString(user);
      request.add(newIndexRequest().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();}}

3.3 根据id删除文档

/**
 * 直接根据id删除
 */publicclassESTestDocDeleteById{publicstaticvoidmain(String[] args)throwsException{//创建es客户端RestHighLevelClient esClient =newRestHighLevelClient(RestClient.builder(newHttpHost("127.0.0.1",9200)));System.out.println(esClient);//构建删除请求DeleteRequest request =newDeleteRequest("user");
        request.id("1003");DeleteResponse response = esClient.delete(request,RequestOptions.DEFAULT);System.out.println(response.getResult());//关闭客户端连接
        esClient.close();}}

3.4 根据id批量删除

/**
 * 根据id数组批量删除
 */publicclassESTestDocDeleteBulk{publicstaticvoidmain(String[] args)throwsException{//创建es客户端RestHighLevelClient esClient =newRestHighLevelClient(RestClient.builder(newHttpHost("127.0.0.1",9200)));System.out.println(esClient);BulkRequest request =newBulkRequest("user");List<String> idList  =Arrays.asList("1,2,3,4".split(","));for(String id : idList){
            request.add(newDeleteRequest().index("user").id(id));}BulkResponse response = esClient.bulk(request,RequestOptions.DEFAULT);System.out.println(response.getTook());System.out.println(response.getItems());//关闭客户端连接
        esClient.close();}}

3.5 根据id部分修改

​ 这里说的是部分修改,整体覆盖修改参考带id新增

/**
 * 直接根据id部分修改
 */publicclassESTestDocUpdate{publicstaticvoidmain(String[] args)throwsException{//创建es客户端RestHighLevelClient esClient =newRestHighLevelClient(RestClient.builder(newHttpHost("127.0.0.1",9200)));System.out.println(esClient);//修改数据 部分修改UpdateRequest request =newUpdateRequest();
        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();}}

4、JAVA内查询doc

4.1 根据id查询文档

/**
 * 直接根据id查找
 */publicclassESTestDocQueryById{publicstaticvoidmain(String[] args)throwsException{//创建es客户端RestHighLevelClient esClient =newRestHighLevelClient(RestClient.builder(newHttpHost("127.0.0.1",9200)));System.out.println(esClient);//查询数据GetRequest request =newGetRequest("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();}}

4.2 查询全部 matchAll

privatestaticvoidqueryALl(RestHighLevelClient esClient)throwsException{//查询索引中的全部数据SearchRequest request =newSearchRequest();
  request.indices("user");//查询全部 matchAll
  request.source(newSearchSourceBuilder().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());}}

4.3 条件查询

privatestaticvoidqueryCondition(RestHighLevelClient esClient)throwsException{//查询索引中的全部数据SearchRequest request =newSearchRequest();
  request.indices("user");//分词中 同时包含李强才可以,因为底层默认使用英文分词器,所以李强会被分为 李,强没办法符合条件所以查询不到//request.source(new SearchSourceBuilder().query(QueryBuilders.termQuery("name","李强")));//这样是李强字段不可再分,查询name字段中包含此字段的数据
  request.source(newSearchSourceBuilder().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());}}

4.4 分页查询、部分字段显示、排序

privatestaticvoidqueryPage(RestHighLevelClient esClient)throwsException{SearchRequest request =newSearchRequest();
    request.indices("user");//构造查询条件SearchSourceBuilder query =newSearchSourceBuilder().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());}}

4.5 组合条件查询

privatestaticvoidqueryConditionS(RestHighLevelClient esClient)throwsException{SearchRequest request =newSearchRequest();
        request.indices("user");//构造查询条件SearchSourceBuilder builder =newSearchSourceBuilder();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 范围查询

privatestaticvoidqueryBetween(RestHighLevelClient esClient)throwsException{SearchRequest request =newSearchRequest();
    request.indices("user");//构造查询条件SearchSourceBuilder builder =newSearchSourceBuilder();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());}}

4.7 模糊查询(不针对中文)

privatestaticvoidqueryLike(RestHighLevelClient esClient)throwsException{SearchRequest request =newSearchRequest();
  request.indices("user");//构造查询条件SearchSourceBuilder builder =newSearchSourceBuilder();
  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());}}

4.8 高亮查询

privatestaticvoidqueryHighLighter(RestHighLevelClient esClient)throwsException{SearchRequest request =newSearchRequest();
    request.indices("user");//构造查询条件SearchSourceBuilder builder =newSearchSourceBuilder();TermQueryBuilder termQueryBuilder =QueryBuilders.termQuery("name","zhang");HighlightBuilder highlightBuilder =newHighlightBuilder();
    highlightBuilder.preTags("<h1 color='red'>");
    highlightBuilder.postTags("</h1>");
    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());}}

4.8 聚合查询(最大值)

privatestaticvoidqueryAggregation(RestHighLevelClient esClient)throwsException{SearchRequest request =newSearchRequest();
    request.indices("user");//构造查询条件SearchSourceBuilder builder =newSearchSourceBuilder();//分组名称,聚合字段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());}}

4.9 聚合查询(group分组)

privatestaticvoidqueryGroup(RestHighLevelClient esClient)throwsException{SearchRequest request =newSearchRequest();
    request.indices("user");//构造查询条件SearchSourceBuilder builder =newSearchSourceBuilder();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());}}


本文转载自: https://blog.csdn.net/qq_27331467/article/details/125849796
版权归原作者 LvhaoIT 所有, 如有侵权,请联系我们删除。

“ElasticSearch(四)Java中使用ES”的评论:

还没有评论