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"));
    }

}
08-30 03:52