ElasticSearch API记录

ElasticSearch API记录,第1张

ElasticSearch API记录 ElasticSearch API

依赖管理


    1.8
    
    7.6.1



    org.springframework.boot
    spring-boot-starter-data-elasticsearch

定义配置类

@Configuration
public class ElasticSearchConfig {
    // 注册 rest高级客户端 
    @Bean
    public RestHighLevelClient restHighLevelClient(){
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("127.0.0.1",9200,"http")
                )
        );
        return client;
    }
}
APIS 索引 *** 作
// 测试索引的创建, Request PUT demo_index
@Test
public void testCreateIndex() throws IOException {
    CreateIndexRequest request = new CreateIndexRequest("demo_index");
    CreateIndexResponse response = restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
    // 查看是否创建成功
    System.out.println(response.isAcknowledged());
	// 查看返回对象
    System.out.println(response);
    restHighLevelClient.close();
}

// 测试获取索引,并判断其是否存在
@Test
public void testIndexIsExists() throws IOException {
    GetIndexRequest request = new GetIndexRequest("index");
    boolean exists = restHighLevelClient.indices().exists(request, RequestOptions.DEFAULT);
    // 索引是否存在
    System.out.println(exists);
    restHighLevelClient.close();
}


// 测试索引删除
@Test
public void testDeleteIndex() throws IOException {
    DeleteIndexRequest request = new DeleteIndexRequest("demo_index");
    AcknowledgedResponse response = restHighLevelClient.indices().delete(request, RequestOptions.DEFAULT);
    // 是否删除成功
    System.out.println(response.isAcknowledged());
    restHighLevelClient.close();
}
文档 *** 作
// 文档添加
@Test
public void testAdddocument() throws IOException {
    User demo = new User("demo", 18);
    // 创建请求
    IndexRequest request = new IndexRequest("demo_index");
    // 制定规则 PUT /demo_index/_doc/1
    request.id("1");// 设置文档ID
    request.timeout(Timevalue.timevalueMillis(1000));// request.timeout("1s")
    // 将我们的数据放入请求中
    request.source(JSON.toJSONString(demo), XContentType.JSON);
    // 客户端发送请求,获取响应的结果
    IndexResponse response = restHighLevelClient.index(request, RequestOptions.DEFAULT);
    System.out.println(response.status());// 获取建立索引的状态信息 CREATED
    System.out.println(response);// 查看返回内容 IndexResponse[index=demo_index,type=_doc,id=1,version=1,result=created,seqNo=0,primaryTerm=1,shards={"total":2,"successful":1,"failed":0}]
}


// 测试获得文档信息
@Test
public void testGetdocument() throws IOException {
    GetRequest request = new GetRequest("demo_index","1");
    GetResponse response = restHighLevelClient.get(request, RequestOptions.DEFAULT);
    // 打印文档内容
    System.out.println(response.getSourceAsString());
    // 返回的全部内容和命令是一样的
    System.out.println(request);
    restHighLevelClient.close();
}

// 获取文档,判断是否存在 get /demo_index/_doc/1
@Test
public void testdocumentIsExists() throws IOException {
    GetRequest request = new GetRequest("demo_index", "1");
    // 不获取返回的 _source的上下文了
    request.fetchSourceContext(new FetchSourceContext(false));
    request.storedFields("_none_");
    boolean exists = restHighLevelClient.exists(request, RequestOptions.DEFAULT);
    System.out.println(exists);
}


// 测试更新文档内容
@Test
public void testUpdatedocument() throws IOException {
    UpdateRequest request = new UpdateRequest("demo_index", "1");
    User user = new User("lmk",11);
    request.doc(JSON.toJSONString(user),XContentType.JSON);
    UpdateResponse response = restHighLevelClient.update(request, RequestOptions.DEFAULT);
    // OK
    System.out.println(response.status()); 
    restHighLevelClient.close();
}

// 测试删除文档
@Test
public void testDeletedocument() throws IOException {
    DeleteRequest request = new DeleteRequest("demo_index", "1");
    request.timeout("1s");
    DeleteResponse response = restHighLevelClient.delete(request, RequestOptions.DEFAULT);
    // OK
    System.out.println(response.status());
}

// 查询
// SearchRequest 搜索请求
// SearchSourceBuilder 条件构造
// HighlightBuilder 高亮
// TermQueryBuilder 精确查询
// MatchAllQueryBuilder
// xxxQueryBuilder ...
@Test
public void testSearch() throws IOException {
    // 1.创建查询请求对象
    SearchRequest searchRequest = new SearchRequest();
    // 2.构建搜索条件
    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    // (1)查询条件 使用QueryBuilders工具类创建
    // 精确查询
    TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "demo");
    //        // 匹配查询
    //        MatchAllQueryBuilder matchAllQueryBuilder = QueryBuilders.matchAllQuery();
    // (2)其他<可有可无>:(可以参考 SearchSourceBuilder 的字段部分)
    // 设置高亮
    searchSourceBuilder.highlighter(new HighlightBuilder());
    //        // 分页
    //        searchSourceBuilder.from();
    //        searchSourceBuilder.size();
    searchSourceBuilder.timeout(new Timevalue(60, TimeUnit.SECONDS));
    // (3)条件投入
    searchSourceBuilder.query(termQueryBuilder);
    // 3.添加条件到请求
    searchRequest.source(searchSourceBuilder);
    // 4.客户端查询请求
    SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
    // 5.查看返回结果
    SearchHits hits = search.getHits();
    System.out.println(JSON.toJSONString(hits));
    System.out.println("=======================");
    for (SearchHit documentFields : hits.getHits()) {
        System.out.println(documentFields.getSourceAsMap());
    }
}


// 上面的这些api无法批量增加数据(只会保留最后一个source)
@Test
public void test() throws IOException {
    IndexRequest request = new IndexRequest("bulk");// 没有id会自动生成一个随机ID
    request.source(JSON.toJSONString(new User("liu",1)),XContentType.JSON);
    request.source(JSON.toJSONString(new User("min",2)),XContentType.JSON);
    request.source(JSON.toJSONString(new User("kai",3)),XContentType.JSON);
    IndexResponse index = restHighLevelClient.index(request, RequestOptions.DEFAULT);
    // created
    System.out.println(index.status());
}


// 特殊的,真的项目一般会 批量插入数据
@Test
public void testBulk() throws IOException {
    BulkRequest bulkRequest = new BulkRequest();
    bulkRequest.timeout("10s");
    ArrayList users = new ArrayList<>();
    users.add(new User("demo-1",1));
    users.add(new User("demo-2",2));
    users.add(new User("demo-3",3));
    users.add(new User("demo-4",4));
    users.add(new User("demo-5",5));
    users.add(new User("demo-6",6));
    // 批量请求处理
    for (int i = 0; i < users.size(); i++) {
        bulkRequest.add(
                // 这里是数据信息
                new IndexRequest("bulk")
                        .id(""+(i + 1)) // 没有设置id 会自定生成一个随机id
                        .source(JSON.toJSONString(users.get(i)),XContentType.JSON)
        );
    }
    BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
    System.out.println(bulk.status());// ok
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5679227.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存