SpringBoot2.0.2z整合ES(默认3.0.7)

一:安装:

1)在linux下载并安装elasticsearch在虚拟机上

2)增加用户 sudo adduser username  然后切换用户 sudo username(root用户不能启动服务)

3)对elasticsearch文件权限进行修改。chown usergroup:name  elasticsearch -R(授权)

4)进入config文件夹,对文件配置  vim jvm.options 设置最大最小堆内存。然后 vim elasticsearch.yml设置data文件夹和logs文件夹(ES对虚拟机存储占用比较大)

5) 进入bin目录 运行脚本 ./elasticsearch

二:操作

 1.pom文件,版本很重要,不然起都起不来

<!-- Spring Boot Elasticsearch 依赖 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<!--需要引入transport-netty3-client,否则会启动报错-->
<dependency>
    <groupId>org.elasticsearch.plugin</groupId>
    <artifactId>transport-netty3-client</artifactId>
    <version>5.6.10</version>
</dependency>

2.配置Bean

@Configuration
public class ElasticSearchConfig {
    private static final Logger logger = LoggerFactory.getLogger(ElasticSearchConfig.class);

    @PostConstruct
    void init() {
        System.setProperty("es.set.netty.runtime.available.processors", "false");
    }
    @Bean
    public TransportClient transportClient() {
        logger.info("初始化");
        TransportClient client = null;
        try {
            TransportAddress transportAddress = new InetSocketTransportAddress(InetAddress.getByName("localhost"),
                    Integer.valueOf(9300));
            // 配置信息
            Settings esSetting = Settings.builder()
                    .put("cluster.name","elasticsearch") //节点名称
                    .build();
            //配置信息Settings自定义
            client = new PreBuiltTransportClient(esSetting);
            client.addTransportAddresses(transportAddress);
        } catch (Exception e) {
            logger.error("elasticsearch TransportClient create error!!!", e);
        }
        return client;
    }
}

3.实体类

@Data
@AllArgsConstructor
@NoArgsConstructor
@Document(indexName="chuyun",type="article",indexStoreType="fs",shards=5,replicas=1,refreshInterval="-1")
    public class Article {
        //文章ID,这里必须为 id
        @Id
        private Long id;
        //标题
        private String title;
        //内容
        private String content;
        //浏览量
        private Integer viewCount;
        //发布时间
        private Date createTime;
        //更新时间
        private Date updateTime;

}
dao层  //不用实现
public interface ArticleRepository extends ElasticsearchRepository<Article, Long> {

   List<Article> findByTitle(String title);
}

4.测试类

package top.hkf.demo.redistest.demo;


import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.junit.Before;
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.PageImpl;
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.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.test.context.junit4.SpringRunner;
import top.hkf.demo.dao.ArticleRepository;
import top.hkf.demo.entity.Article;
import org.springframework.data.domain.Page;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RunWith(SpringRunner.class)
@SpringBootTest
public class ESTest {
    @Autowired
    private ArticleRepository articleRepository;

    @Autowired
    private ElasticsearchTemplate template;

    @Test
    public void initRepositoryData() {
        template.createIndex(Article.class);//创建索引库
     
        Article article = new Article();
        article.setId((long) 1);
        article.setTitle("xxx");
        article.setContent("aaa,bbb,ccc");
        article.setCreateTime(new Date());
        article.setUpdateTime(new Date());
        article.setViewCount(678);
        articleRepository.save(article);
   
    }

    @Test
    public void findDistinctByTitleContainingOrContentContainingTest() throws Exception {
        String title = "xxx";
        List<Article> list = articleRepository.findByTitle(title);
//        List<Long> collect = list.stream().filter(article -> {
//            return article.getId() > 5;
//        }).map(Article::getId).collect(Collectors.toList());
    }

    //自定义查询,根据命名规则
    @Test
    public void findByTitleAndContent() {
        Pageable pageable = PageRequest.of(0, 2);//分页,从0开始,不分页默认没页10条
        articleRepository.findByTitleAndContent("zs", "123", pageable);
    }

    //先分词,在查询,分词之间是and关系,即所有分词都应在一段话中
    //需求是只要包含任何一个词即可查出来,即queryString,queryTerm
    @Test
    public void testNativeSearchQuery() {
        //创建查询对象
        NativeSearchQuery nativeSearchQuery = new NativeSearchQueryBuilder()
                .withQuery(QueryBuilders.queryStringQuery("123").defaultField("title"))
                .withPageable(PageRequest.of(0, 3)).build();
        //执行查询
        List<Article> articles = template.queryForList(nativeSearchQuery, Article.class);
        articles.forEach(a -> System.out.println(a));
    }

    //高亮显示,字段,前缀,后缀。在执行查询之前设置高亮显示
    @Test
    public void testFilter() {
        List<Article> list=Arrays.asList(new Article(1l,"123","123"),
                new Article(5l,"123","123"),
                new Article(6l,"123","123"),
                new Article(7l,"123","123"),
                new Article(8l,"123","123"));

       list.stream().filter(article ->
           article.getId() > 5
        ).map(Article::getId).collect(Collectors.toList()).forEach(a-> System.out.println(a));
    }

}

执行成功后,head里面就会有索引库,索引库的定义在实体类中。

 

image.png

 

注解说明:

@Documnet 注解

public @interface Document {

 

String indexName(); //索引库的名称,个人建议以项目的名称命名

 

String type() default ""; //类型,个人建议以实体的名称命名

 

short shards() default 5; //默认分区数

 

short replicas() default 1; //每个分区默认的备份数

 

String refreshInterval() default "1s"; //刷新间隔

 

String indexStoreType() default "fs"; //索引文件存储类型

}

@Field注解

public @interface Field {

 

FieldType type() default FieldType.Auto; //自动检测属性的类型,可以根据实际情况自己设置

 

FieldIndex index() default FieldIndex.analyzed; //默认情况下分词,一般默认分词就好,除非这个字段你确定查询时不会用到

 

DateFormat format() default DateFormat.none; //时间类型的格式化

 

String pattern() default ""; 

 

boolean store() default false; //默认情况下不存储原文

 

String searchAnalyzer() default ""; //指定字段搜索时使用的分词器

 

String indexAnalyzer() default ""; //指定字段建立索引时指定的分词器

 

String[] ignoreFields() default {}; //如果某个字段需要被忽略

 

boolean includeInParent() default false;

}

 

总结:错误1

java.lang.IllegalStateException: availableProcessors is already set to [4], rejecting [4]

在注入bean时,执行

@PostConstruct
    void init() {
        System.setProperty("es.set.netty.runtime.available.processors", "false");
    }

错误2:java访问端口为9300,http访问为9200

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章