• springBoot04_检索


    前言:本文只是记录用springBoot整合Elasticsearch的过程,之后会详细做一篇关于Elastisearch。

    1.1 Elasticsearch 简介

    我们的应用经常需要添加检索功能,开源的 ElasticSearch 是目前全文搜索引擎的首选。他可以快速的存储、搜索和分析海量数据。Spring Boot通过整合Spring Data ElasticSearch为我们提供了非常便捷的检索功能支持。
      Elasticsearch是一个分布式搜索服务,提供Restful API,底层基于Lucene,采用多shard(分片)的方式保证数据安全,并且提供自动resharding的功能。

    官方中文文档请参考:https://www.elastic.co/guide/cn/index.html
    官方文档有详细的使用指南,可自行翻阅学习。

    一个 Elasticsearch 集群可以包含多个索引(类比MySQL数据库),相应的每个索引可以包含多个类型(类比Mysql表)。 这些不同的类型存储着多个文档(类比Mysql行) ,每个文档又有多个属性(类比Mysql字段)。可以类比MySQL进行理解。

    2.1 安装Elasticsearch

    这里是在Docker中安装Elasticsearch,步骤如下:

    • 下载镜像
    docker pull docker.io/elasticsearch
    
    • 运行镜像
       Elasticsearch是使用Java写的,它默认初始占用两个G的堆内存空间,如果我们是在虚拟机上测且虚拟机的内存不够将无法运行成功。
    docker run -e ES_JAVA_OPTS="-Xms256m -Xmx256m" -d -p 9200:9200 -p 9300:9300 --name ES01 imageid
    #-Xms256m:设置初始的堆内存大小为256兆
    #-Xmx256m:设置最大使用的堆内存大小为256m
    #elasticsearch默认外部通信使用9200端口,分布式下各个节点间的通信使用9300端口
    
    
    • 测试
      打开浏览器访问虚拟机的9200端口,当出现json数据响应便证明安装成功。

    3.1 整合Elasticsearch

    SpringBoo支持Jest和SpringData ElasticSearch两种技术来和ES交互,其中Jest默认不生效,如果想让其生效需要导入jest的工具包(io.searchbox.client.JestClient),SpringData ElasticSearch默认生效但ES版本有可能不适配。

    3.1.1 SpringBoot整合Jest操作ES

    • 引入依赖
    <!-- https://mvnrepository.com/artifact/io.searchbox/jest -->
    <dependency>
    	<groupId>io.searchbox</groupId>
    	<artifactId>jest</artifactId>
    	<version>5.3.3</version>
    </dependency>
    
    
    • 进行配置
    spring.elasticsearch.jest.uris=http://192.168.1.16:9200
    
    
    • 在实体类中指定主键
    public class Article {
    	//指定主键
        @JestId
        private Integer id;
        private String author;
        private String title;
        private String content;
    
    
    • 测试JestClient
    @RunWith(SpringRunner.class)
    @SpringBootTest
    public class Springboot03ElasticApplicationTests {
    
    	@Autowired
    	JestClient jestClient;
    
    	@Test
    	public void contextLoads() {
    		//1、给Es中索引(保存)一个文档;
    		Article article = new Article();
    		article.setId(1);
    		article.setTitle("好消息");
    		article.setAuthor("zhangsan");
    		article.setContent("Hello World");
    
    		//构建一个索引功能
    		Index index = new Index.Builder(article).index("sk").type("news").build();
    
    		try {
    			//执行
    			jestClient.execute(index);
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    	}
    
    	//测试搜索
    	@Test
    	public void search(){
    
    		//查询表达式
    		String json ="{
    " +
    				"    "query" : {
    " +
    				"        "match" : {
    " +
    				"            "content" : "hello"
    " +
    				"        }
    " +
    				"    }
    " +
    				"}";
    
    		//构建搜索功能
    		Search search = new Search.Builder(json).addIndex("sk").addType("news").build();
    
    		//执行
    		try {
    			SearchResult result = jestClient.execute(search);
    			System.out.println(result.getJsonString());
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    	}
    }
    
    

    更多操作请参考:https://github.com/searchbox-io/Jest/tree/master/jest

    3.1.2 整合SpringData Elasticsearch

    SpringData Elasticsearch的相关配置类帮我们自动配置了一个连接ES的客户端Client,一个操作ES的ElasticsearchTemplate。
      客户端Client需要我们指定clusterNodes和clusterName两个节点信息。
      SpringData Elasticsearch除了为我们提供了ElasticsearchTemplate来操作ES外还给我们提供了编写一个 ElasticsearchRepository 子接口来操作ES的方式。
      如果版本不匹配,我们可以升级SpringBoot版本也可以安装对应版本的ES。

    版本适配说明:https://github.com/spring-projects/spring-data-elasticsearch

    • 引入依赖
    <!--SpringBoot默认使用SpringData ElasticSearch模块进行操作-->
    <dependency>
    	<groupId>org.springframework.boot</groupId>
    	<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
    </dependency>
    
    
    • 配置
    spring.data.elasticsearch.cluster-name=elasticsearch
    spring.data.elasticsearch.cluster-nodes=192.168.1.16:9301
    
    • 使用

    共有两种用法,参考:https://github.com/spring-projects/spring-data-elasticsearch

    编写一个 ElasticsearchRepository:

    //该注解标注数据存储到哪个索引、哪个类型下
    @Document(indexName = "sk",type = "book")
    public class Book {
        private Integer id;
        private String bookName;
        private String author;
    
    
    //两个泛型分别是要存取数据的类型和要存取数据的主键类型
    public interface BookRepository extends ElasticsearchRepository<Book,Integer> {
    
        //自定义方法的命名规则请参考官方文档
       public List<Book> findByBookNameLike(String bookName);
    }
    
    
    @RunWith(SpringRunner.class)
    @SpringBootTest
    public class Springboot03ElasticApplicationTests {
    
    	@Autowired
    	BookRepository bookRepository;
    
    	@Test
    	public void test02(){
    //		Book book = new Book();
    //		book.setId(1);
    //		book.setBookName("西游记");
    //		book.setAuthor("吴承恩");
    //		bookRepository.index(book); 索引(存储)数据,存储在哪个索引、类型下在实体类中用注解标注。
    		for (Book book : bookRepository.findByBookNameLike("游")) {//匹配所有带“游”的文档。
    			System.out.println(book);
    		}
    	}
    }
    
    

    更多使用请参考官方文档:https://docs.spring.io/spring-data/elasticsearch/docs/3.0.6.RELEASE/reference/html/

  • 相关阅读:
    AgileEAS.NET平台视频会议培训第二辑简单插件开发应用演练(速度下载)
    给大家分享一个培训的PPT:面向构件的组织级开发模式探讨
    AgileEAS.NET SOA 中间件平台工作流系统介绍
    “医疗信息化行业之中的联发科” 我们在医疗行业中的定位及目标
    AgileEAS.NET SOA 平台5.1开发包介绍
    实例演示如何使用AgileEAS.NET SOA平台工作流进行业务流程自定义
    Silverlight企业应用开发实践AgileEAS.NET平台5.0 Silverlight支撑预览
    AgileEAS.NET平台视频会议培训第三辑插件的安装、配置以及账户权限系统演练
    Stream Part.6
    Stream Part.7
  • 原文地址:https://www.cnblogs.com/xhj928675426/p/13169087.html
Copyright © 2020-2023  润新知