ElasticSearch(四)Java中使用ES

Java内使用ES

文章目录

  • Java内使用ES
    • 1、JAVA整合ElasticSearch
    • 2、JAVA内操作索引
      • 2.1 创建索引
      • 2.2 获取索引信息
      • 2.3 删除索引信息
    • 3、JAVA内增删改doc
      • 3.1 新增文档信息
      • 3.2 批量新增文档信息
      • 3.3 根据id删除文档
      • 3.4 根据id批量删除
      • 3.5 根据id部分修改
    • 4、JAVA内查询doc
      • 4.1 根据id查询文档
      • 4.2 查询全部 matchAll
      • 4.3 条件查询
      • 4.4 分页查询、部分字段显示、排序
      • 4.5 组合条件查询
      • 4.7 模糊查询(不针对中文)
      • 4.8 高亮查询
      • 4.8 聚合查询(最大值)
      • 4.9 聚合查询(group分组)


1、JAVA整合ElasticSearch

  1. 导入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>
    
  2. 编写测试类,尝试获取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();
      }
    }
    

2、JAVA内操作索引

2.1 创建索引

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();
    }
}

2.2 获取索引信息

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();
    }
}

2.3 删除索引信息

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();
    }
}

3、JAVA内增删改doc

创建一个实体类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;
    }
}

3.1 新增文档信息

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();
    }
}

3.2 批量新增文档信息

/**
 * 根据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();
  }
}

3.3 根据id删除文档

/**
 * 直接根据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();
    }
}

3.4 根据id批量删除

/**
 * 根据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();
    }
}

3.5 根据id部分修改

​ 这里说的是部分修改,整体覆盖修改参考带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();
    }
}

4、JAVA内查询doc

4.1 根据id查询文档

/**
 * 直接根据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();
    }
}

4.2 查询全部 matchAll

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());
  }
}

4.3 条件查询

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());
  }
}

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

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());
    }
}	

4.5 组合条件查询

    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());
    }
}

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

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());
  }
}

4.8 高亮查询

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()); } }

4.8 聚合查询(最大值)

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());
    }
}

4.9 聚合查询(group分组)

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());
    }
}

你可能感兴趣的:(大数据,elasticsearch,java,大数据)