ElasticSearch入门(3)——Spring实践

ElasticSearch入门(3)——Spring实践

简单的入门之后就是实践

基于SpringBoot

<properties>
        <java.version>1.8java.version>
        <elasticsearch.version>7.6.2elasticsearch.version>
    properties>

    <dependencies>

        
            
            
            
        

        <dependency>
            <groupId>org.elasticsearch.clientgroupId>
            <artifactId>elasticsearch-rest-high-level-clientartifactId>
            <version>7.6.2version>
        dependency>

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-data-elasticsearchartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-devtoolsartifactId>
            <scope>runtimescope>
            <optional>trueoptional>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-configuration-processorartifactId>
            <optional>trueoptional>
        dependency>
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <optional>trueoptional>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintagegroupId>
                    <artifactId>junit-vintage-engineartifactId>
                exclusion>
            exclusions>
        dependency>
    dependencies>

ElasticSearch版本要指定

ElasticSearch配置类

@Configuration
public class ElasticSearchConfig {

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

单元测试

实体类

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @author gyh
 * @csdn https://blog.csdn.net/qq_40788718
 * @date 2020/8/4 16:46
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {

    private String name ;

    private Integer age ;

}

测试类


import com.alibaba.fastjson.JSON;
import com.gyh.esapi.entity.User;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.search.fetch.subphase.FetchSourceContext;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;
import java.util.*;

@SpringBootTest
class EsApiApplicationTests {

    @Autowired
    private RestHighLevelClient restHighLevelClient ;

    //增加

    /**
     * 创建索引
     * @throws IOException
     */
    @Test
    void testCreateOneIndex() throws IOException {
        //创建索引
        CreateIndexRequest request = new CreateIndexRequest("kuang_index") ;
        //执行创建索引请求
        CreateIndexResponse response = restHighLevelClient.indices().create(request , RequestOptions.DEFAULT) ;
        System.out.println(response.index());
    }

    /**
     * 单个插入
     */
    @Test
    void testCreateOneSource() throws IOException {
        User user = new User("狂神说Java" , 2) ;
        IndexRequest request = new IndexRequest("kuang_index") ;
        request.id("2") ;
        request.timeout(TimeValue.timeValueSeconds(1)) ;
        request.timeout("1s") ;

        request.source(JSON.toJSONString(user) , XContentType.JSON) ;

        IndexResponse response = restHighLevelClient.index(request , RequestOptions.DEFAULT) ;

        System.out.println(response.status()); //CREATED

    }

    /**
     * 批量插入
     */
    @Test
    void testCreateBulkSource() throws IOException {
        BulkRequest request = new BulkRequest("kuang_index") ;
        request.timeout("10s") ;
        for (int i=10 ; i<30 ; i++){
            User user = new User(UUID.randomUUID().toString().substring(0, 5), (int) (Math.random() * 100)) ;
            IndexRequest indexRequest = new IndexRequest("kuang_index");
            indexRequest.id(""+i) ;
            indexRequest.source(JSON.toJSONString(user) , XContentType.JSON) ;
            request.add(indexRequest) ;
        }
        BulkResponse response = restHighLevelClient.bulk(request, RequestOptions.DEFAULT);
        System.out.println(response.status());
        System.out.println(response.hasFailures());
        System.out.println(response.toString());
        //OK
        //false
        //org.elasticsearch.action.bulk.BulkResponse@718f805a
    }


    //删除

    /**
     * 删除单个文档
     * @throws IOException
     */
    @Test
    void testDeleteOneSource() throws IOException {
        DeleteRequest request = new DeleteRequest("kuang_index" , "1") ;
        request.timeout("1s");
        DeleteResponse response = restHighLevelClient.delete(request, RequestOptions.DEFAULT);
        System.out.println(response.status());
        System.out.println(response.toString());
        //OK
        //DeleteResponse[index=kuang_index,type=_doc,
        //id=1,version=4,result=deleted,
        //shards=ShardInfo{total=2, successful=1, failures=[]}]
    }

    void testDeleteBulkSource(){
        //和批量插入相同
    }

    //修改

    /**
     * 更新文档
     * @throws IOException
     */
    @Test
    void testUpdateOneSource() throws IOException {
        UpdateRequest request = new UpdateRequest("kuang_index" , "1") ;
        User user = new User("gyh说Java" ,10) ;
        request.timeout("1s") ;
        request.doc(JSON.toJSONString(user) , XContentType.JSON) ;
        UpdateResponse update = restHighLevelClient.update(request, RequestOptions.DEFAULT);
        System.out.println(update.status());
        System.out.println(update.toString());
        //OK
        //UpdateResponse[index=kuang_index,type=_doc,id=1,version=2,seqNo=1,
        //primaryTerm=1,result=updated,shards=ShardInfo{total=2, successful=1, failures=[]}]

    }


    /**
     * 批量更新
     */
    @Test
    void testUpdateBulkSource() throws IOException {
        //和批量插入相同
        BulkRequest request = new BulkRequest("kuang_index") ;
        request.timeout("10s") ;
        for (int i=20 ; i<30 ; i++){
            //或者根据json更新
            request.add(new UpdateRequest("kuang_index" , ""+i).doc("age" , 10)) ;
        }
        BulkResponse response = restHighLevelClient.bulk(request, RequestOptions.DEFAULT);
        System.out.println(response.status());
        System.out.println(response.hasFailures());
        System.out.println(response.toString());
        //OK
        //false
        //org.elasticsearch.action.bulk.BulkResponse@17b016ac
    }

    //查询

 /**
     * 条件查询
     */
    @Test
    void testSearch() throws IOException {
        SearchRequest request = new SearchRequest("kuang_index");
        SearchSourceBuilder builder = new SearchSourceBuilder();
        TermQueryBuilder query = QueryBuilders.termQuery("name", "");
//        QueryBuilders.matchQuery() ; =
//        QueryBuilders.matchQuery() ;
//        QueryBuilders.termQuery() ;
//        QueryBuilders.boolQuery() ;
//        QueryBuilders.boolQuery().should() ;
//        QueryBuilders.matchAllQuery() ;
        builder.query(query) ;
//        builder.from() ;
//        builder.size() ;
//        builder.profile() ;
//        builder.postFilter() ;
        builder.timeout(new TimeValue(60 , TimeUnit.SECONDS)) ;
        request.source(builder) ;
        SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
        System.out.println(response.status());
        System.out.println(JSON.toJSONString(response.getHits()));
        SearchHit[] hits = response.getHits().getHits();
        for (SearchHit hit : hits) {
            System.out.println(hit.getSourceAsMap());
        }
        
    }


    /**
     * 获取单个doc
     * @throws IOException
     */
    @Test
    void testSelectOneSource() throws IOException {
        boolean flag = isExist("kuang_index" , "1") ;
        GetRequest request = new GetRequest("kuang_index" , "1") ;
        GetResponse response = restHighLevelClient.get(request , RequestOptions.DEFAULT) ;
        System.out.println(response.getVersion());
        System.out.println(response.getSource().toString());
        //1
        //{name=狂神说Java, age=3}
    }

    /**
     * 判断是否存在
     * @param id
     * @return
     */
    boolean isExist(String index , String id) throws IOException {
        GetRequest request = new GetRequest(index , id) ;
        //不获取_source的上下文
        request.fetchSourceContext(new FetchSourceContext(false)) ;
        request.storedFields("_none_") ;
        boolean flag = restHighLevelClient.exists(request , RequestOptions.DEFAULT) ;
        return flag ;
    }

}

你可能感兴趣的:(ElasticSearch)