您的位置:首页 > 编程语言 > Java开发

springboot整合elasticsearch全文检索入门

2018-10-23 21:25 615 查看

钉钉、微博极速扩容黑科技,点击观看阿里云弹性计算年度发布会!>>>

只是简单的整合介绍

# 安装

下载elasticsearch与kibana https://www.elastic.co/start

# 依赖

  1. springBootVersion = '2.0.5.RELEASE'

  2. compile group: 'org.springframework.boot', name: 'spring-boot-starter-data-elasticsearch'

  3. //请与spring-boot-starter-data-elasticsearch的jar包版本一致

  4. compile('org.elasticsearch.client:transport:5.6.11')

springBoot 2.0.5.RELEASE 起步依赖的elasticsearch的版本是 5.6.11 

# 配置

1. 可在application.yml中配置

  1. spring:

  2.  data:

  3.    # 全文检索 elasticsearch

  4.    elasticsearch:

  5.      cluster-name: elasticsearch #节点名称

  6.      cluster-nodes: 127.0.0.1:9300 #节点地址

  7.      repositories:

  8.        enabled: true


2. 也可以通过java代码进行配置

  1. package com.futao.springmvcdemo.foundation.configuration

  2. import org.elasticsearch.client.transport.TransportClient

  3. import org.elasticsearch.common.settings.Settings

  4. import org.elasticsearch.common.transport.InetSocketTransportAddress

  5. import org.elasticsearch.transport.client.PreBuiltTransportClient

  6. import org.springframework.context.annotation.Bean

  7. import org.springframework.context.annotation.Configuration

  8. import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories

  9. import java.net.InetAddress

  10. /**

  11. * @author futao

  12. * Created on 2018/10/22.

  13. * ElasticSearch全文检索配置类

  14. * 可替代配置文件中的配置

  15. */

  16. @Configuration

  17. @EnableElasticsearchRepositories(basePackages = ["com.futao.springmvcdemo.dao"])

  18. open class ElasticSearchConfiguration {

  19.    @Bean

  20.    open fun client(): TransportClient {

  21.        val node = InetSocketTransportAddress(

  22.                InetAddress.getByName("127.0.0.1"), 9300)

  23.        val settings = Settings.builder()

  24.                .put("cluster.name", "springboot-elasticsearch")    //集群名称可以在\elasticsearch\config\elasticsearch.yml中配置

  25.                .build()

  26.        return PreBuiltTransportClient(settings).addTransportAddress(node)

  27.    }

  28. }

# 名词解释

elasticsearch中的名词与mysql中的名字对比 

# 使用

个人理解:相当于mysql的建表,程序跑起来之后elasticsearch会建立相应的index与type,后续程序中就可以使用该类型的index与type进行crud

  1. package com.futao.springmvcdemo.model.entity;

  2. import org.springframework.data.elasticsearch.annotations.Document;

  3. /**

  4. * @author futao

  5. * Created on 2018/10/20.

  6. * 文章

  7. * indexName=database

  8. * type=table

  9. * row=document

  10. * colnum=field

  11. */

  12. @Document(indexName = "futao", type = "article")

  13. public class Article extends BaseEntity {

  14.    /**

  15.     * 标题

  16.     */

  17.    private String title;

  18.    /**

  19.     * 简介

  20.     */

  21.    private String description;

  22.    /**

  23.     * 内容

  24.     */

  25.    private String content;

  26.    public String getTitle() {

  27.        return title;

  28.    }

  29.    public void setTitle(String title) {

  30.        this.title = title;

  31.    }

  32.    public String getDescription() {

  33.        return description;

  34.    }

  35.    public void setDescription(String description) {

  36.        this.description = description;

  37.    }

  38.    public String getContent() {

  39.        return content;

  40.    }

  41.    public void setContent(String content) {

  42.        this.content = content;

  43.    }

  44. }

# 插入数据

  • Dao层

  1. package com.futao.springmvcdemo.dao.impl

  2. import com.futao.springmvcdemo.model.entity.Article

  3. import org.springframework.data.elasticsearch.repository.ElasticsearchRepository

  4. /**

  5. * @author futao

  6. * Created on 2018/10/22.

  7. */

  8. interface ArticleSearchDao : ElasticsearchRepository<Article, String> {

  9. }

  • Service层

  1. package com.futao.springmvcdemo.service.impl

  2. import com.alibaba.fastjson.JSONObject

  3. import com.futao.springmvcdemo.dao.ArticleDao

  4. import com.futao.springmvcdemo.dao.impl.ArticleSearchDao

  5. import com.futao.springmvcdemo.foundation.LogicException

  6. import com.futao.springmvcdemo.model.entity.Article

  7. import com.futao.springmvcdemo.model.entity.constvar.ErrorMessage

  8. import com.futao.springmvcdemo.service.ArticleService

  9. import com.futao.springmvcdemo.utils.currentTimeStamp

  10. import com.futao.springmvcdemo.utils.getFieldName

  11. import com.futao.springmvcdemo.utils.uuid

  12. import org.elasticsearch.client.Client

  13. import org.elasticsearch.index.query.QueryBuilders

  14. import org.springframework.data.redis.core.RedisTemplate

  15. import org.springframework.stereotype.Service

  16. import javax.annotation.Resource

  17. /**

  18. * @author futao

  19. * Created on 2018/10/20.

  20. */

  21. @Service

  22. open class ArticleServiceImpl : ArticleService {

  23.    @Resource

  24.    private lateinit var elasticsearch: ArticleSearchDao

  25.    @Resource

  26.    private lateinit var client: Client

  27.    override fun list(): List<Article> {

  28.        val list = articleDao.list()

  29.    //将数据放入elasticsearch中

  •        elasticsearch.saveAll(list)

  •        return list

  •    }

  • /**

  •     * 全文检索

  •     */

  •    override fun search(key: String): ArrayList<Article> {

  •        val hits = client.prepareSearch("futao")

  •                .setTypes("article")

  •                .setQuery(

  •                        QueryBuilders

  •                                .boolQuery()

  •                                .should(QueryBuilders.matchQuery(Article::getContent.getFieldName(), key))

  •                                .should(QueryBuilders.matchQuery(Article::getTitle.getFieldName(), key))

  •                                .should(QueryBuilders.matchQuery(Article::getDescription.getFieldName(), key))

  •                )

  •                .execute()

  •                .actionGet()

  •                .hits

  •        val list: ArrayList<Article> = arrayListOf()

  •        hits.forEach { it -> list.add(JSONObject.parseObject(it.sourceAsString, Article::class.java)) }

  •        return list

  •    }

  • }

    • controller层

    1. package com.futao.springmvcdemo.controller.business;

    2. import com.futao.springmvcdemo.model.entity.Article;

    3. import com.futao.springmvcdemo.model.entity.SingleValueResult;

    4. import com.futao.springmvcdemo.service.ArticleService;

    5. import org.springframework.http.MediaType;

    6. import org.springframework.web.bind.annotation.*;

    7. import javax.annotation.Resource;

    8. import java.util.List;

    9. /**

    10. * @author futao

    11. * Created on 2018/10/20.

    12. */

    13. @RestController

    14. @RequestMapping(path = "article", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)

    15. public class ArticleController {

    16.    @Resource

    17.    private ArticleService articleService;

    18.    /**

    19.     * 新增文章

    20.     *

    21.     * @param title

    22.     * @param desc

    23.     * @param content

    24.     * @return

    25.     */

    26.    @PostMapping(path = "add")

    27.    public SingleValueResult add(

    28.            @RequestParam("title") String title,

    29.            @RequestParam("desc") String desc,

    30.            @RequestParam("content") String content

    31.    ) {

    32.        articleService.add(title, desc, content);

    33.        return new SingleValueResult("success");

    34.    }

    35.    /**

    36.     * 文章列表

    37.     *

    38.     * @return

    39.     */

    40.    @GetMapping("list")

    41.    public List<Article> list() {

    42.        return articleService.list();

    43.    }

    44.    /**

    45.     * 全文检索

    46.     *

    47.     * @param key

    48.     * @return

    49.     */

    50.    @GetMapping("search")

    51.    public List<Article> search(@RequestParam("key") String key) {

    52.        return articleService.search(key);

    53.    }

    54. }

    • 在启动项目之前如果程序有抛出 

      java.lang.IllegalStateException:availableProcessorsisalreadysetto[4],rejecting[4]
      异常,则需要在启动类中添加:

    1. package com.futao.springmvcdemo;

    2. import com.alibaba.fastjson.parser.ParserConfig;

    3. import org.mybatis.spring.annotation.MapperScan;

    4. import org.springframework.boot.SpringApplication;

    5. import org.springframework.boot.autoconfigure.SpringBootApplication;

    6. import org.springframework.boot.web.servlet.ServletComponentScan;

    7. import org.springframework.cache.annotation.EnableCaching;

    8. import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories;

    9. /**

    10. * @author futao

    11. * ServletComponentScan 开启servlet和filter

    12. */

    13. @SpringBootApplication

    14. < 2000 span class="lit" style="box-sizing: border-box;color: rgb(223, 83, 32);line-height: 20px;font-size: 13px !important;white-space: inherit !important;">@ServletComponentScan

    15. @MapperScan("com.futao.springmvcdemo.dao")

    16. @EnableCaching

    17. //@EnableAspectJAutoProxy

    18. @EnableElasticsearchRepositories(basePackages = "com.futao.springmvcdemo")

    19. public class SpringmvcdemoApplication {

    20.    public static void main(String[] args) {

    21.        /**

    22.         * 添加elasticsearch之后发生异常的解决方案

    23.         * Springboot整合Elasticsearch 在项目启动前设置一下的属性,防止报错

    24.         * 解决netty冲突后初始化client时会抛出异常

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

    26.         */

    27.        System.setProperty("es.set.netty.runtime.available.processors", "false");

    28.        SpringApplication.run(SpringmvcdemoApplication.class, args);

    29.        /**

    30.         * redis反序列化

    31.         * 开启fastjson反序列化的autoType

    32.         */

    33.        ParserConfig.getGlobalInstance().setAutoTypeSupport(true);

    34.    }

    35. }

    # 测试

    • 启动项目,可以在health中查看到相关的健康状况 

    • list接口请求(把数据放入elasticsearch中) 

    • 现在可以在kibana中查看到上面存入的数据 

    • 也可以进行简单的搜索测试 

    • 调用search接口测试 

    elasticsearch数据的存放位置(删除该文件夹下的数据即删除了所有的索引) 

    多的不说了,跟之前项目中用过的Hibernate Search很像,不过elasticsearch也是在架构层面实现的全文索引,elasticsearch可以部署在其他服务器上,减轻主服务器的压力,并通过http restful api的形式与主程序进行协调工作。elasticsearch一般通过集群方式进行部署,横向扩展非常简单,甚至只需要改几行配置就行。


    本文分享自微信公众号 - 喜欢天文(AllUnderControl)。
    如有侵权,请联系 support@oschina.cn 删除。
    本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。

    内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息