java操作es之rest风格基本操作

ES基本操作

文章目录

1、注入RestHighLevelClient

@Configuration
public class ElasticSearchClientConfig {
    @Bean
    public RestHighLevelClient restHighLevelClient(){
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(new HttpHost("39.105.145.159",9200,"http"))
        );
        return client;
    }
}

2、操作索引

注入RestHighLevelClient

@Autowired
@Qualifier("restHighLevelClient")
RestHighLevelClient client;

2.1、创建索引

​ PUT index

void testIndex() {
        //1.创建索引的请求
        CreateIndexRequest request = new CreateIndexRequest("test_index");
        //2客户端执行请求,请求后获得响应
        CreateIndexResponse response = null;
        try {
            response = client.indices().create(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(response);
    }

2.2、测试索引是否存在 GET index

void testExistIndex() throws IOException {
    //1.创建索引的请求
    GetIndexRequest request = new GetIndexRequest("test_index");
    //2客户端执行请求,请求后获得响应
    boolean exist =  client.indices().exists(request, RequestOptions.DEFAULT);
    System.out.println("测试索引是否存在-----"+exist);
}

2.3、删除索引 DELETE index

void testDeleteIndex() throws IOException {
    DeleteIndexRequest request = new DeleteIndexRequest("test_index");
    AcknowledgedResponse delete = client.indices().delete(request, RequestOptions.DEFAULT);
    System.out.println("删除索引--------" + delete.isAcknowledged());
}

3、文档操作

3.1、添加文档

void testAddDocument() throws IOException {
    //创建对象
    User user = new User("小明",18);
    //创建请求
    IndexRequest request = new IndexRequest("test_index");
    //制定规则
    request.id("1");//id
    request.timeout(TimeValue.timeValueSeconds(1));//过期时间
    //request.timeout("1s");

    //将数据放入请求
    request.source(JSON.toJSONString(user), XContentType.JSON);
    //客户端发送请求
    IndexResponse indexResponse = client.index(request, RequestOptions.DEFAULT);

}

3.2、获取文档,查看是否存在

void testIsExists() throws IOException {
    GetRequest getRequest = new GetRequest("test_index", "1");
    getRequest.fetchSourceContext(new FetchSourceContext(false));//不获取_source的上下文,效率更高
    getRequest.storedFields("_none_");

    boolean exists = client.exists(getRequest,RequestOptions.DEFAULT);
    System.out.println(exists);

}

3.3、获取文档信息

void testGetDocument() throws IOException{
    GetRequest getRequest = new GetRequest("test_index", "1");
    GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT);
    System.out.println(getResponse.getSourceAsString());//打印文档内容
    System.out.println(getResponse);//返回的全部内容和命令获取的是一样的
}

3.4、更新文档

void testUpdateDocument() throws IOException{
    UpdateRequest updateRequest = new UpdateRequest("test_index", "1");
    updateRequest.timeout("1s");
    User user = new User("小明", 10);
    updateRequest.doc(JSON.toJSONString(user),XContentType.JSON);
    UpdateResponse update = client.update(updateRequest, RequestOptions.DEFAULT);
    System.out.println(update.status());
    System.out.println(update);
}

3.5、删除1号文档

void testDeleteDocument() throws IOException{
    DeleteRequest deleteRequest = new DeleteRequest("test_index", "1");
    deleteRequest.timeout("1s");
    DeleteResponse delete = client.delete(deleteRequest, RequestOptions.DEFAULT);
    System.out.println(delete);
    System.out.println(delete.status());
}

3.6、批量插入数据

void testBulkDocument() throws IOException {
    BulkRequest bulkRequest = new BulkRequest();
    bulkRequest.timeout("10s");//数据越大时间越多

    ArrayList<User> arrayList = new ArrayList<>();
    arrayList.add(new User("小明",10));
    arrayList.add(new User("小红",11));
    arrayList.add(new User("小1",12));
    arrayList.add(new User("小2",13));
    arrayList.add(new User("小3",14));
    arrayList.add(new User("小4",15));

    //批处理请求
    for(int i = 0;i<arrayList.size();i++){
        bulkRequest.add(
                new IndexRequest("test_index")
                        .id(""+(i+1))
                .source(JSON.toJSONString(arrayList.get(i)),XContentType.JSON)
        );
    }
    BulkResponse bulk = client.bulk(bulkRequest, RequestOptions.DEFAULT);
    System.out.println(bulk.hasFailures());//是否失败  false:成功    true:失败

}

3.7、查询,分页,高亮

void testSearch() throws IOException {
    ArrayList<Map<String,Object>> list = new ArrayList<>();
    SearchRequest searchRequest = new SearchRequest("test_index");
    //构建搜索条件
    SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

    //查询条件,可以使用QueryBuilders  因为中文愿意查不出中文,所以将name改为name.keyword,也可以安装ik分词器
    TermQueryBuilder termQuery = QueryBuilders.termQuery("name.keyword", "小红");//精确查询
    sourceBuilder.query(termQuery);


    //匹配所有
    /*MatchAllQueryBuilder allQueryBuilder = QueryBuilders.matchAllQuery();
    sourceBuilder.query(allQueryBuilder);*/


    //在60s内查询出来
    sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));

    //分页
    sourceBuilder.from(0);
    sourceBuilder.size(4);

    //高亮显示
    HighlightBuilder highlightBuilder = new HighlightBuilder();
    highlightBuilder.field("name.keyword");
    highlightBuilder.requireFieldMatch(false);  //多个单词高亮的话,要把这个设置为trues
    highlightBuilder.preTags("<span style='color:red'>");
    highlightBuilder.postTags("</span>");
    sourceBuilder.highlighter(highlightBuilder);

    //执行搜索
    searchRequest.source(sourceBuilder);
    SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);//执行请求

    for (SearchHit hit : searchResponse.getHits().getHits()) {
        //解析高亮,用高亮替换原来的
        Map<String, HighlightField> highlightFields = hit.getHighlightFields();
        HighlightField name = highlightFields.get("name.keyword");
        Map<String, Object> sourceAsMap = hit.getSourceAsMap();//原来的结果
        if(name!=null){
            Text[] fragments = name.fragments();
            StringBuilder newName = new StringBuilder();
            for (Text text : fragments) {
                newName.append(text);
            }
            sourceAsMap.put("name", newName.toString());
            list.add(sourceAsMap);
        }
    }
    System.out.println(list.toString());
}

4、查询

4.1、整体结构

  • 注入RestHighLevelClient

    @Autowired
    @Qualifier("restHighLevelClient")
    RestHighLevelClient client;
    
  • 搜索框架

    void findByName() throws IOException {
      SearchRequest searchRequest = new SearchRequest("test_index");
      //构建搜索条件
      SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
      //存储多个条件
      BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
      //构建条件
      TermQueryBuilder query1 = QueryBuilders.termQuery("name.keyword","小明");
      //条件放入
      queryBuilder.should(query1);
      //多条件引入
      sourceBuilder.query(queryBuilder);
      //进行分页
      sourceBuilder.from(0);
      sourceBuilder.size(6);
      //条件进入请求
      searchRequest.source(sourceBuilder);
      //执行查询
      SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
      //解析查询结果
      for (SearchHit hit : search.getHits().getHits()) {
          System.out.println(hit.getSourceAsMap().toString());
      }
    }
    

4.2、常用条件查询

4.2.1、精度匹配查询 termQuery

TermQueryBuilder query1 = QueryBuilders.termQuery("name.keyword","小明");

根据名字查询,查询name,加上keyword是由于中文匹配,keyword不会进行分词,才能够进行查询,不加keyword默认是text,会进行分词

4.2.2、匹配查询(分词)matchQuery

MatchQueryBuilder name = QueryBuilders.matchQuery("name", "小明");

查询结果:java操作es之rest风格基本操作

它会将“小明”分为“小”与“明”进行查询,所以将“小兰”也查出来了

4.2.3、精确查询 queryString

//构建条件QueryStringQueryBuilder name = new QueryStringQueryBuilder("小兰").field("name").defaultOperator(Operator.AND);

使用QueryStringQueryBuilder构造查询条件,不用keyword也可以精确查询。

4.2.4、模糊查询 wildcardQuery

WildcardQueryBuilder wildcardQuery = QueryBuilders.wildcardQuery("name.keyword", String.format("*%s*", "小"));

查询结果:java操作es之rest风格基本操作

小字进行模糊查询。

4.2.5、范围查询 rangeQuery

RangeQueryBuilder age = QueryBuilders.rangeQuery("age").from(12, true).to(15, true);

后面的true表示包含当前值即:[12,15],若为false则为(12,15)。

4.2.6、多条件合并查询

//搜索条件WildcardQueryBuilder wildcardQuery1 = QueryBuilders.wildcardQuery("name.keyword", String.format("*%s*", "小"));WildcardQueryBuilder wildcardQuery2 = QueryBuilders.wildcardQuery("name.keyword", String.format("*%s*", "兰"));queryBuilder.must(wildcardQuery1).must(wildcardQuery2);

查询结果:java操作es之rest风格基本操作

这里使用的是must进行合并查询,代表and,使用should即代表or,可以分开写也可以合在一条语句。

保存笔记,以后总能用得着。

上一篇:动态分区分配(java) 操作系统实验


下一篇:luogu P3919 [模板]可持久化数组(可持久化线段树/平衡树)(主席树)