ElasticSearch(2)---SpringBoot整合ElasticSearch

SpringBoot整合ElasticSearch

 

一、基于spring-boot-starter-data-elasticsearch整合

 开发环境:springboot版本:2.0.1,elasticSearch-5.6.8.jar版本:5.6.8,服务器部署ElasticSearch版本:6.3.2

1、application.properties

spring.data.elasticsearch.cluster-name=elasticsearch
spring.data.elasticsearch.cluster-nodes=127.0.0.1:9300
spring.data.elasticsearch.repositories.enabled=true

2、pom.xml

        <!--spring整合elasticsearch包-->
        <dependency>  
           <groupId>org.springframework.boot</groupId>  
           <artifactId>spring-boot-starter-data-elasticsearch</artifactId>  
       </dependency>

        <!--实体工具包-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

        <!--集合工具包-->
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>19.0</version>
        </dependency>

3、Notice实体

@Data
@AllArgsConstructor
@NoArgsConstructor
//indexName代表所以名称,type代表表名称
@Document(indexName = "wantu_notice_info", type = "doc")
public class Notice {

    //id
    @JsonProperty("auto_id")
    private Long id;

    //标题
    @JsonProperty("title")
    private String title;

    //公告标签
    @JsonProperty("exchange_mc")
    private String exchangeMc;

    //公告发布时间
    @JsonProperty("create_time")
    private String originCreateTime;

    //公告阅读数量
    @JsonProperty("read_count")
    private Integer readCount;
    
}

4、NoticeRepository类

import com.jincou.elasearch.domain.Notice;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.stereotype.Component;

@Component
public interface NoticeRepository extends ElasticsearchRepository<Notice, Long> {

} 

5、NoticeController

@RestController
@RequestMapping("/api/v1/article")
public class NoticeController {


    @Autowired
    private NoticeRepository nticeRepository;
    
    @GetMapping("save")
    public CommandResult<Void> save(long id, String title){
    
        Notice article = new Notice();
        article.setId(id);
        article.setReadCount(123);
        article.setTitle("springboot整合elasticsearch,这个是新版本 2018年");
        nticeRepository.save(article);
        return CommandResult.ofSucceed();
    }


    /**
     * @param title   搜索标题
     * @param pageable page = 第几页参数, value = 每页显示条数
     */
    @GetMapping("search")
    public CommandResult<List<Notice>> search(String title,@PageableDefault(page = 1, value = 10) Pageable pageable){
//按标题进行搜索 QueryBuilder queryBuilder
= QueryBuilders.matchQuery("title", title);
//如果实体和数据的名称对应就会自动封装,pageable分页参数 Iterable
<Notice> listIt = nticeRepository.search(queryBuilder,pageable);
//Iterable转list List
<Notice> list= Lists.newArrayList(listIt); return CommandResult.ofSucceed(list); } }

6、查看运行结果

它会进行中文分词查询,然后安装相识度进行排序

总体步骤还是蛮清晰简单的,因为有spring-boot-starter-data-elasticsearch进行了整合,所以我们可以少敲很多代码。

 

二、 基于TransportClient整合

首先明白:如果项目SpringBoot1.5.X以下的,那么elasticSearch.jar最高是2.4.4版本的,只有SpringBoot2.X+,elasticSearch.jar才是5.X+

              如果你的SpringBoot是1.5.X以下,那你又想用elasticSearch.jar5.X+怎么办呢,那就不要用spring-boot-starter-data-elasticsearch,用原生的TransportClient实现即可。

这个相当于用原生的去使用elasticsearch,这里面并没有用到spring-boot-starter-data-elasticsearch相关jar包,因为我们公司的springBoot版本是1.5.9。

如果用spring-boot-starter-data-elasticsearch的话,那么elasticsearch版本最高只有2.4.4,这也太落后了,现在elasticsearch已经到6.3.2了,为了用更好的版本有两个方案:

1、提高springboot版本到2.X(不过不现实,船大难掉头),2、用原生的TransportClient实现。最终落地实现是通过TransportClient实现

把关键代码展示出来。

1、pom.xml

    <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>5.6.8</version>
        </dependency>


        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>transport</artifactId>
            <version>5.6.8</version>
        </dependency>

        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.7</version>
        </dependency>

2、创建实体

    @Configuration
    public class ServerModule {

        @Bean
        public TransportClient transportClient() {
            Settings settings = Settings.builder().put("cluster.name", "biteniuniu").build();
            //我用6.3.2版本的时候这里一直报异常说找不到InetSocketTransportAddress类,这应该和jar有关,当我改成5.6.8就不报错了
            TransportClient client = new PreBuiltTransportClient(settings);//6.3.2这里TransportAddress代替InetSocketTransportAddress
            client.addTransportAddress(new InetSocketTransportAddress(
                    new InetSocketAddress(InetAddresses.forString("127.0.0.1"), 9300)));
            return client;
        }
    }

3、NoticeController类

@RestController
@RequestMapping("/api/v1/notice")
public class NoticeController {
    

    @Autowired
    private TransportClient transportClient;
    
    /**
     *利用TransportClient实现搜索功能
     * @param title   搜索标题
     * @param  page = 从第几条结果返回 | Integer(比如一次size=20,page=0,如果要显示下一页20条记录则需要size=20,page=20)这个和之前有点区别, size = 每页显示条数
     */

    @RequestMapping(value = "trsearch", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public CommandResult<List<Notice>> search(@RequestParam(value = "title", defaultValue = "比特币")String title, @RequestParam(value = "page", defaultValue = "0")Integer page,
                                                              @RequestParam(value = "size", defaultValue = "20")Integer size) {

        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        //按标题进行查找
        boolQueryBuilder.must(QueryBuilders.matchQuery("title", title));
        
//在这里输入索引名称和type类型 SearchResponse response
= transportClient.prepareSearch("wantu_notice_info").setTypes("doc") // 设置查询类型java .setSearchType(SearchType.DFS_QUERY_THEN_FETCH) // 设置查询关键词 .setQuery(boolQueryBuilder) // 设置查询数据的位置,分页用 .setFrom(page) // 设置查询结果集的最大条数 .setSize(size) // 设置是否按查询匹配度排序 .setExplain(true) // 最后就是返回搜索响应信息 .get(); SearchHits searchHits = response.getHits(); List<Notice> list = Lists.newArrayListWithCapacity(size); for (SearchHit searchHit : searchHits) { Map<String, Object> sourceAsMap = searchHit.getSourceAsMap(); //获得titie数据 String titles = (String) sourceAsMap.get("title"); //获得阅读量数据 Integer readCount = (Integer) sourceAsMap.get("read_count"); //把数据装入对象中 Notice notice=new Notice(); notice.setTitle(titles); notice.setReadCount(readCount); list.add(notice); } return CommandResult.ofSucceed(list); } }

4、运行结果

 总结下:第一种整合相对简单很多,因为本身封装很多东西,比如分页,封装数据等。第二种的话可以在不用spring的情况下使用它。

 

 我只是偶尔安静下来,对过去的种种思忖一番。那些曾经的旧时光里即便有过天真愚钝,也不值得谴责。毕竟,往后的日子,还很长。不断鼓励自己,

 天一亮,又是崭新的起点,又是未知的征程(上校4)

 

  

posted on 2018-08-23 21:23  雨点的名字  阅读(26188)  评论(7编辑  收藏  举报