1. 程式人生 > >ES-使用springData來操作es

ES-使用springData來操作es

1 Es 的配置檔案 elasticsearch.yml


http.cors.enabled: true
http.cors.allow-origin: "*"

network.host: 127.0.0.1

2 配置中文分詞器 (見之前的部落格)

3 匯入jar

<?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.1.7.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.example</groupId>
	<artifactId>demo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>demo</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</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>

		<dependency>
			 <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
         </dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-test</artifactId>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

4 編寫配置檔案 (7.3 暫時springdata暫時不支援)

# elasticsearch-6.5.4 需要再配置檔案配置上ip地址
spring.data.elasticsearch.cluster-name=elasticsearch
spring.data.elasticsearch.cluster-nodes=127.0.0.1:9300
#設定連線超時時間
spring.data.elasticsearch.properties.transport.tcp.connect_timeout=120s

5 實體類上增加註解

/**
 * @author shihaifeng
 * @date 2019-08-29 14:06
 * @desc (描述)
 **/
@Document(indexName = "book",type = "user")
public class Book implements Serializable{
    @Id     //主鍵
    private Integer id;

    @Field(type = FieldType.Text, analyzer = "ik_max_word")
    private String name;

    @Field(type = FieldType.Text, analyzer = "ik_max_word")
    private String context;

    @Field(type = FieldType.Text, analyzer = "ik_smart")
    private String auto;
}

 

6 編寫介面

package com.example.demo.inter;

import com.example.demo.entity.Book;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;

/**
 * @author shihaifeng
 * @date 2019-08-29 14:47
 * @desc (書介面 - 用來直接操作)
 *
 *  Book 實體物件
 *  Integer 是主鍵
 **/
public interface IBookServer extends ElasticsearchRepository<Book,Integer> {
}

7 測試

package com.example.demo;

import com.example.demo.entity.Book;
import com.example.demo.inter.IBookServer;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.SearchResultMapper;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.aggregation.impl.AggregatedPageImpl;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.*;

;

/**
 * @author shihaifeng
 * @date 2019-08-29 14:52
 * @desc (描述)
 **/
@RunWith(SpringRunner.class)
@SpringBootTest
public class BookTest {

    @Autowired
    private IBookServer bookServer;

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    /**
     * 新增資料
     */
    @Test
    public void addBook() {
        //新增一條資料
        bookServer.save(new Book(1, "書名", "書內容", "作者"));

        List<Book> list = new ArrayList<>();
        list.add(new Book(2, "《阿彌陀佛麼麼噠》", "大冰,本名焉冰,1980年10月23日出生於山東省煙臺市萊陽市,中國內地主持人、民謠歌手、作家、油畫畫師,畢業於山東藝術學院。", "大冰"));
        list.add(new Book(3, "《我不》", "善意能消戾,善意能得緣,善意能帶業往生,善意能回頭是岸。 善意能夠幫人捕捉並建立起獨特的幸福感。 “我不”是一種善意坦然,也是一種善意的隨緣,更是一句善意的自省", "大冰"));
        list.add(new Book(4, "《乖,摸摸頭》", "是由主持人大冰所著,湖南文藝出版社的一本記錄了大冰十餘年的江湖遊歷,以及他和他朋友們的愛與溫暖的傳奇故事的書籍。", "大冰"));
        list.add(new Book(5, "《他們最幸福》", "書中講述的故事是有關於主角大冰一段十年的精彩生長之路,也是路途中十個不同他們幸福的故事,更是一段對當下價值觀有形無聲的生活抗議。 多棲身份的大冰,從主持人到民謠歌手,從江湖遊俠到資深文青,他抱著一隻手鼓行唱在天涯中,卻從未將故事寫在紙面上。", "大冰"));

        list.add(new Book(6, "《邊城》", "沈從文的創作風格趨向浪漫主義,他要求小說的詩意效果,融寫實、紀夢、象徵於一體,語言格調古樸,\n" +
                "沈從文及其作品沈從文及其作品(5張)句式簡峭、主幹突出,單純而又厚實,樸訥而又傳神", "沈從文"));
        list.add(new Book(7, "《湘行散記》", "沈從文是具有特殊意義的鄉村世界的主要表現者和反思者,他認為“美在生命”,雖身處於虛偽、自私和冷漠的都市,卻醉心於人性之美", "沈從文"));
        list.add(new Book(8, "《長河》", "“我不知道為什麼忽然愛上你了。”身為任課教師的沈從文悄悄地給學生張兆和寫信,他在信裡這麼說。", "沈從文"));
        bookServer.saveAll(list);//批量新增資料
    }

    /**
     * 查詢資訊
     */
    @Test
    public void query() {
        Optional<Book> book = bookServer.findById(3);
        System.out.println("------------findById-----------------");
        System.out.println(book.get().toString());

        Iterable<Book> books = bookServer.findAll();
        System.out.println("------------findAll-----------------");
        for (Book book1 : books) {
            System.out.println(book1);
        }

        System.out.println("------------search QueryBuilder-----------------");
        Page<Book> search = bookServer.search(new TermQueryBuilder("context", "沈從文"), PageRequest.of(0, 10));
        for (Book book1 : search.getContent()) {
            System.out.println(book1);
        }

        System.out.println("------------search SearchQuery (高亮顯示)-----------------");
        NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
                .withQuery(QueryBuilders.termQuery("context", "沈從文"))       //設定查詢內容
                .withHighlightFields(new HighlightBuilder.Field("context").preTags("<字首>").postTags("</字尾>")).build()  //設定高亮顯示
                .setPageable(PageRequest.of(0, 10));//設定分頁資訊
        AggregatedPage<Book> page = elasticsearchTemplate.queryForPage(searchQuery, Book.class, new SearchResultMapper() {
            @Override
            public <T> AggregatedPage<T> mapResults(SearchResponse searchResponse, Class<T> aClass, Pageable pageable) {
                //返回結果集重新對映
                List<Book> list = new ArrayList<>();

                SearchHits hits = searchResponse.getHits();
                Iterator<SearchHit> iterator = hits.iterator();
                while (iterator.hasNext()){
                    Book book = new Book();
                    SearchHit searchHit = iterator.next();

                    Map<String, Object> source = searchHit.getSourceAsMap();
                    book.setId(Integer.valueOf(source.get("id").toString()));//設定id
                    book.setName(source.get("name").toString());//設定書名
                    book.setAuto(source.get("auto").toString());//設定作者

                    Map<String, HighlightField> highlightFields = searchHit.getHighlightFields();//獲取高亮顯示的列
                    book.setContext(highlightFields.get("context").toString());//設定高亮顯示的列
                    System.out.println("高亮顯示的值是 = " + highlightFields.get("context"));

                    list.add(book);
                }

                //返回查詢的結果
                return new AggregatedPageImpl(list);
            }
        });
        List<Book> content = page.getContent();
        System.out.println("查出的總數是 = " + content.size());
    }


    /**
     * 跟新資料
     */
    @Test
    public void update(){
        bookServer.save(new Book(1, "書名3", "書內容3", "作者3"));
    }

    /**
     * 刪除資料
     */
    @Test
    public void delete(){
        bookServer.delete(new Book(1, "書名3", "書內容3", "作者3"));
    }

}