58、ElasticSearch 和SpingBoot集成、实战小Demo

1、添加Pom.xml 依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.0.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.kuang.elasticsearch</groupId>
    <artifactId>es_demo01</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>es_demo01</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

2、创建配置类

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

}

3、创建测试类,对索引进行操作

@SpringBootTest
class EsDemo01ApplicationTests {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    /**
     * 创建索引
     * @throws IOException
     */
    @Test
    void createTest() throws IOException {
        CreateIndexRequest request = new CreateIndexRequest("kuang_index");
        CreateIndexResponse response = restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
        System.out.println("==================="+response);
    }
    
    /**
     * 查询索引是否存在
     * @throws IOException
     */
    @Test
    void indexExsit() throws IOException {
        GetIndexRequest request = new GetIndexRequest("kuang_index");
        Boolean exist = restHighLevelClient.indices().exists(request, RequestOptions.DEFAULT);
        System.out.print("=================="+exist);
    }
    
    /**
     * 删除索引库
     * @throws IOException
     */
    @Test
    void indexDelete() throws IOException {
        DeleteIndexRequest request = new DeleteIndexRequest("kuang_index");
        AcknowledgedResponse delete = restHighLevelClient.indices().delete(request, RequestOptions.DEFAULT);
        System.out.print("=================="+delete.isAcknowledged());
    }

}

四、对文档的操作(重点)

1、插入一条数据

/**
     * 插入一条数据
     * 
     * @throws IOException
     */
    @Test
    void createDocument() throws IOException {
        User user = new User();
        user.setName("危存盛");
        user.setAge(11);
        user.setBirthday(new Date());
        user.setTags(new String[] { "泡妞", "玩游戏" });
        IndexRequest request = new IndexRequest("kuang_index");
        request.id("1");
        request.timeout(TimeValue.timeValueSeconds(1));
        request.source(JSON.toJSONString(user), XContentType.JSON);
        IndexResponse index = restHighLevelClient.index(request, RequestOptions.DEFAULT);
        System.out.println(index.toString());
        System.out.println(index.status());
    }

2、获取数据

/**
     * 获取数据
     * 
     * @throws IOException
     */
    @Test
    void getDocument() throws IOException {
        GetRequest getRequest = new GetRequest("kuang_index", "1");
        GetResponse response = restHighLevelClient.get(getRequest, RequestOptions.DEFAULT);
        System.out.println(response.getSourceAsString());
        System.out.println(response);
    }

3、更新数据

/**
     * 更新文档
     * 
     * @throws IOException
     */
    @Test
    void testUpdateDoc() throws IOException {
        UpdateRequest updateRequest = new UpdateRequest("kuang_index", "1");
        User user = new User();
        user.setName("大帅哥");
        updateRequest.doc(JSON.toJSONString(user), XContentType.JSON);

        UpdateResponse response = restHighLevelClient.update(updateRequest, RequestOptions.DEFAULT);

        System.out.println(response.status());
    }

4、删除数据

/**
     * 删除文档记录
     * 
     * @throws IOException
     */
    @Test
    void testDeleteDoc() throws IOException {
        DeleteRequest deleteRequest = new DeleteRequest("kuang_index", "1");
        DeleteResponse response = restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);
        System.out.println(response.status());
    }

5、批量插入数据

    @Test
    void testBlukDocument() throws IOException {
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout("10s");

        List<User> userList = new ArrayList<>();
        userList.add(new User("edwin", 22, new Date()));
        userList.add(new User("yanglingfang", 11, new Date()));
        userList.add(new User("yangfang", 33, new Date()));
        userList.add(new User("shunxiaomeng", 23, new Date()));
        userList.add(new User("wuxiaoxiao", 31, new Date()));

        for (int i = 0; i < userList.size(); i++) {
            bulkRequest.add(new IndexRequest("kuang_index").id("" + i).source(JSON.toJSONString(userList.get(i)),
                    XContentType.JSON));
        }
        BulkResponse response = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);

        System.out.println("=================>" + response.hasFailures());
    }

6、构建复杂的查询

/**
     * 查询构建,复杂查询
     * @throws IOException
     */
    @Test
    void testShearch() throws IOException {
        //构建查询请求
        SearchRequest searchRequest = new SearchRequest("kuang_index");
        //构建查询资源
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        //构建查询条件
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "edwin");
        sourceBuilder.query(termQueryBuilder);
        sourceBuilder.timeout(new TimeValue(10,TimeUnit.SECONDS));
        searchRequest.source(sourceBuilder);
        //发送请求
        SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        
        System.out.println(JSON.toJSONString(response.getHits()));
        
        SearchHit[] datas = response.getHits().getHits();
        for(SearchHit data: datas) {
            System.out.println(data.getSourceAsMap());
        }
    }

 

posted @ 2021-09-20 00:48  shunnWcs  阅读(39)  评论(0)    收藏  举报