Elasticsearch学习笔记4:Springboot整合ES

Posted Vincent9847

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Elasticsearch学习笔记4:Springboot整合ES相关的知识,希望对你有一定的参考价值。

一、编写ES配置类

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
//Spring两步骤:
//1、找对象
//2、放到spring中待用
@Configuration
public class ElasticSearchClientConfig {
    @Bean
    public RestHighLevelClient restHighLevelClient(){
        RestHighLevelClient client = new RestHighLevelClient(
            RestClient.builder(
                new HttpHost(hostname: "127.0.0.1", port:9200, scheme: "http"))) ;
        return client;
    }
}

二、关于索引的操作

1.创建索引

//面向对象来操作
@Autowired
@Qualifier ("restHighLevelClient")
private RestHighLevelClient client;
//测试索引的创建    Request PUT testdb
@Test
void testCreateIndex () throws IOException {
    //1、创建索引请求
    CreateIndexRequest request =new CreateIndexRequest("testdb") ;
    //2、客户端执行请求 IndicesCLient,请求后获得响应
    CreateIndexResponse createIndexResponse =
            client.indices().create (request,RequestOptions.DEFAULT);
    System.out.println (createIndexResponse) ;
}

2.获取索引

// 测试获取索引,判断其是否存在
@Test
void testExistIndex() throws IOException{
    GetIndexRequest request = new GetIndexRequest (indices: "testdb") ;
    boolean exists = client.indices().exists(request, RequestOptions.DEFAULT) ;
    System.out.println (exists) ;
}

3.删除索引

//测试删除索引
@Test
void testDeleteIndex() throws IOException {
    DeleteIndexRequest request = new DeleteIndexRequest ("testdb") ;
    //删除
    AcknowledgedResponse delete = client.indices().delete (request, RequestOptions. DEFAULT) ;
    System.out.println(delete. isAcknowledged()) ;
}

三、关于文档的操作

1.添加文档

// 测试添加文档
@SneakyThrows
void testAddDocument() throws IOException {
    // 创建对象
    User user =new User(name:"xiaoyi",age:3);
    // 创建请求
    IndexRequest request = new IndexRequest("testdb") ;
    // 规则 put /testdb/_doc/1
    request.id ("1");
    request.timeout(TimeValue.timeValueSeconds(1)) ;
    request.timeout("1s") ;
    //将我们的数据放入请求json
    request.source(JSON.toJSONString(user), XContentType.JSON) ;

    //客户端发送请求,获取响应的结果
    IndexResponse indexResponse = client.index(request, RequestOptions.DEFAULT);
    System.out.println(indexResponse.toString()) ;
    System.out.println(indexResponse.status()) ; |
}

2.获取文档

//获取文档,判断是否存在 get /testdb/doc/1
void testIsExists() throws IOException {
    GetRequest getRequest = new GetRequest(index:"testdb",id:"1") ;
    //不获取返回的_source 的上下文了
    getRequest.fetchSourceContext(new FetchSourceContext(false) ) ;
    getRequest.storedFields("_none_");

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

3.获取文档信息

// 获得文档的信息
@Test
void testGetDocument() throws IOException {
    GetRequest getRequest = new GetRequest( index:"testdb", id:"1");
    GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT);
    System.out.println(getResponse.getSourceAsString());//打印文档的内容
    System.out.println (getResponse);
}

4.更新文档信息

//更新文档的信息
@Test
void testUpdateRequest() throws IOException {
    UpdateRequest updateRequest = new UpdateRequest(index:"testdb", id:"1");
    updateRequest.timeout("1s");
    User user = new User(name:"xiaoyi",age:18);
    updateRequest.doc(JSON.toJSONString(user), XContentType.JSON) ;
    UpdateResponse updateResponse = client.update(updateRequest, RequestOptions.DEFAULT);
    System.out.println(updateResponse.status());
}

5.删除文档信息

//删除文档记录
@Test
void testDeleteRequest() throws IOException{
    DeleteRequest request =new DeleteRequest(index:"testdb",id: "1");
    request.timeout("1s") ;
    DeleteResponse deleteResponse = client.delete(request, RequestOptions.DEFAULT) ;
    System.out.println(deleteResponse.status()) ;
}

四、批量插入记录

//特殊的,真的项目一般都会批量插入数据!
@Test
void testBulkRequest () throws IOException {
    BulkRequest bulkRequest =new BulkRequest() ;
    bulkRequest.timeout("10s") ;
    ArrayList<User> userList = new ArrayList<>();
    userList.add(new User (name: "xiaoyi1", age: 3));
    userList.add(new User (name: "xiaoyi2", age: 3));
    userList.add(new User (name: "xiaoyi3", age: 3));
    userList.add(new User (name: "xiaoer1", age: 3));
    userList.add(new User (name: "xiaoer2", age: 3));
    userList.add(new User (name: "xiaoer3", age: 3));
//批处理请求
    for (int i = Ø; i < userList.size(); i++){
        bulkRequest.add(
            new IndexRequest("testdb")
                .id (""+ (i+1) )
                .source(JSON.toJSONString(userList.get(i)) , XContentType.JSON));
    }
    BulkResponse bulkResponse =client.bulk(bulkRequest, RequestOptions.DEFAULT) ;
    System.out.println(bulkResponse.hasFailures());
}

五、批量查询

// SearchRequest 搜索请求
// SearchSourceBuilder 条件构造
// HighLightBuilder 构建高亮
// TermQueryBuilder 精确查询
// MatchALLQueryBuilder
// xxx QueryBuilder 对应我们刚才看到的命令!
@Test
void testsearch() throws IOException {
    SearchRequest searchRequest = new SearchRequest("testdb");
    //构建搜索条件
    SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
    sourceBuilder.highlighter()
    //查询条件,我们可以使用 QueryBuilders工具来实现
    //QueryBuilders.termQuery 精确
    //QueryBuilders.matchAllQuery()匹配所有
    TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name","xiaoyi");
    //MatchA11QueryBuilder matchAllQueryBuilder=QueryBuilders.matchAllQuery () ;
    sourceBuilder.query(termQueryBuilder) ;
    sourceBuilder.timeout(new TimeValue(60, TimeUnit. SECONDS));
    
    searchRequest.source(sourceBuilder) ;
    
    SearchResponse searchResponse=client.search(searchRequest, RequestOptions.DEFAULT);
    System.out.print1n(JSON.toJSONString(searchResponse.getHits()));
    System.out.println ("==============");

    for(SearchHit documentFields:searchResponse.getHits().getHits()){
    System.out.print1n(documentFields.getSourceAsMap());
    }
}

【更多资源请关注狂神说:https://www.bilibili.com/video/BV17a4y1x7zq

以上是关于Elasticsearch学习笔记4:Springboot整合ES的主要内容,如果未能解决你的问题,请参考以下文章

Elasticsearch学习笔记4:Springboot整合ES

Elasticsearch学习笔记4:Springboot整合ES

Elasticsearch - 尚硅谷(4. Elasticsearch 基本操作_下)学习笔记

Elasticsearch-尚硅谷(8. 优化)学习笔记

Elasticsearch-尚硅谷(8. 优化)学习笔记

Elasticsearch-尚硅谷(8. 优化)学习笔记