zoukankan      html  css  js  c++  java
  • elasticsearch整合spring

    一、项目结构

    二、pom.xml

    <?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
    
        <groupId>org.example</groupId>
        <artifactId>A02elasticsearch</artifactId>
        <version>1.0-SNAPSHOT</version>
    
        <dependencies>
            <!-- https://mvnrepository.com/artifact/org.elasticsearch/elasticsearch -->
            <dependency>
                <groupId>org.elasticsearch</groupId>
                <artifactId>elasticsearch</artifactId>
                <version>7.6.2</version>
            </dependency>
            <!-- https://mvnrepository.com/artifact/org.elasticsearch.client/transport -->
            <dependency>
                <groupId>org.elasticsearch.client</groupId>
                <artifactId>transport</artifactId>
                <version>7.6.2</version>
            </dependency>
            <!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-to-slf4j -->
            <dependency>
                <groupId>org.apache.logging.log4j</groupId>
                <artifactId>log4j-to-slf4j</artifactId>
                <version>2.13.3</version>
            </dependency>
            <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
            <dependency>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-api</artifactId>
                <version>1.7.30</version>
            </dependency>
            <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-simple -->
            <dependency>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-simple</artifactId>
                <version>1.7.30</version>
                <scope>test</scope>
            </dependency>
            <!-- https://mvnrepository.com/artifact/log4j/log4j -->
            <dependency>
                <groupId>log4j</groupId>
                <artifactId>log4j</artifactId>
                <version>1.2.17</version>
            </dependency>
            <!-- https://mvnrepository.com/artifact/junit/junit -->
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.13</version>
                <scope>test</scope>
            </dependency>
            <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-core</artifactId>
                <version>2.11.2</version>
            </dependency>
            <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-databind</artifactId>
                <version>2.11.2</version>
            </dependency>
            <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations -->
            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-annotations</artifactId>
                <version>2.11.2</version>
            </dependency>
            <!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-elasticsearch -->
            <dependency>
                <groupId>org.springframework.data</groupId>
                <artifactId>spring-data-elasticsearch</artifactId>
                <version>4.0.4.RELEASE</version>
                <exclusions>
                    <exclusion>
                        <groupId>org.elasticsearch.plugin</groupId>
                        <artifactId>transport-netty4-client</artifactId>
                    </exclusion>
                </exclusions>
            </dependency>
            <!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-test</artifactId>
                <version>5.2.8.RELEASE</version>
                <scope>test</scope>
            </dependency>
            <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <version>1.18.12</version>
                <scope>provided</scope>
            </dependency>
        </dependencies>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <configuration>
                        <source>1.9</source>
                        <target>1.9</target>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    
    </project>

    三、spring.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:context="http://www.springframework.org/schema/context"
           xmlns:elasticsearch="http://www.springframework.org/schema/data/elasticsearch"
           xsi:schemaLocation="
            http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd
            http://www.springframework.org/schema/data/elasticsearch
            https://www.springframework.org/schema/data/elasticsearch/spring-elasticsearch-1.0.xsd">
        <!--配置客户端-->
        <elasticsearch:transport-client id="esClient" cluster-name="my-elasticsearch"
                                        cluster-nodes="127.0.0.1:9301,127.0.0.1:9302,127.0.0.1:9303"/>
        <!--扫描ElasticsearchRepository接口,继承的接口不需要加注解-->
        <elasticsearch:repositories base-package="com.wuxi.dao"></elasticsearch:repositories>
        <!--客户端整合spring-->
        <bean id="elasticsearchTemplate" class="org.springframework.data.elasticsearch.core.ElasticsearchTemplate">
            <constructor-arg name="client" ref="esClient"></constructor-arg>
        </bean>
    </beans>

    四、bean

    package com.wuxi.bean;
    
    import lombok.Data;
    import org.springframework.data.annotation.Id;
    import org.springframework.data.elasticsearch.annotations.Document;
    import org.springframework.data.elasticsearch.annotations.Field;
    import org.springframework.data.elasticsearch.annotations.FieldType;
    
    @Data
    @Document(indexName = "sdes_blog", type = "_doc", createIndex = false)
    public class Article {
        @Id
        @Field(type = FieldType.Long, store = true)
        private Long id;
        @Field(type = FieldType.Text, store = true, analyzer = "ik_smart")
        private String title;
        @Field(type = FieldType.Text, store = true, analyzer = "ik_smart")
        private String content;
    }

    五、dao

    package com.wuxi.dao;
    
    import com.wuxi.bean.Article;
    import org.springframework.data.domain.Pageable;
    import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
    
    import java.util.List;
    
    /**
     * 查询方法的命名规范,在下图中
     */
    public interface ArticleRepository extends ElasticsearchRepository<Article, Long> {
        List<Article> findByTitle(String title);
    
        List<Article> findByTitleOrContent(String title, String content);
    
        List<Article> findByTitleOrContent(String title, String content, Pageable pageable);
    }

    六、测试

    package com.wuxi.test;
    
    import com.wuxi.bean.Article;
    import com.wuxi.dao.ArticleRepository;
    import org.elasticsearch.index.query.QueryBuilders;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    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.mapping.IndexCoordinates;
    import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
    import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
    import org.springframework.test.context.ContextConfiguration;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    import java.util.Optional;
    
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations = "classpath:spring.xml")
    public class MyElasticSearchTest {
        @Autowired
        private ArticleRepository articleRepository;
        @Autowired
        private ElasticsearchTemplate template;
    
        /**
         * 创建索引库
         *
         * @throws Exception
         */
        @Test
        public void createIndex() throws Exception {
            Map<String, Object> settingsMap = new HashMap<>();
            Map<String, Object> indexMap = new HashMap<>();
            indexMap.put("number_of_shards", "5");
            indexMap.put("number_of_replicas", "1");
            settingsMap.put("index", indexMap);
            template.createIndex(Article.class, settingsMap);
            template.putMapping(Article.class);
        }
    
        /**
         * 添加文档、更新文档
         *
         * @throws Exception
         */
        @Test
        public void addDocument() throws Exception {
            Article article = new Article();
            article.setId(1l);
            article.setTitle("spring整合elasticsearch");
            article.setContent("Elasticsearch是一个基于Lucene的搜索服务器。它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口");
            articleRepository.save(article);
        }
    
        /**
         * 根据id删除文档
         *
         * @throws Exception
         */
        @Test
        public void deleteDocumentById() throws Exception {
            articleRepository.deleteById(1l);
            //删除全部
            //articleRepository.deleteAll();
        }
    
        /**
         * 查询全部文档
         *
         * @throws Exception
         */
        @Test
        public void findAll() throws Exception {
            Iterable<Article> articles = articleRepository.findAll();
            articles.forEach(a -> System.out.println(a));
        }
    
        /**
         * 根据id查询文档
         *
         * @throws Exception
         */
        @Test
        public void testFindById() throws Exception {
            Optional<Article> optional = articleRepository.findById(2l);
            Article article = optional.get();
            System.out.println(article);
        }
    
        /**
         * 根据关键词查询,默认就是分词查询,但是分词之间是并且(and)的关系,可使用原生的分词查询
         *
         * @throws Exception
         */
        @Test
        public void testFindByTitle() throws Exception {
            List<Article> list = articleRepository.findByTitle("spring");
            list.stream().forEach(a -> System.out.println(a));
        }
    
        /**
         * 原生的分词查询
         *
         * @throws Exception
         */
        @Test
        public void testNativeSearchQuery() throws Exception {
            NativeSearchQuery query = new NativeSearchQueryBuilder()
                    .withQuery(QueryBuilders.queryStringQuery("spring是个框架").defaultField("title"))
                    .withPageable(PageRequest.of(0, 10))
                    .build();
            List<Article> articleList = template.queryForList(query, Article.class, IndexCoordinates.of("sdes_blog"));
            articleList.stream().forEach(a -> System.out.println(a));
        }
    
        /**
         * 分页查询
         *
         * @throws Exception
         */
        @Test
        public void testFindPage() throws Exception {
            Pageable pageable = PageRequest.of(0, 10);
            List<Article> list = articleRepository.findByTitleOrContent("spring", "Elasticsearch", pageable);
            list.stream().forEach(a -> System.out.println(a));
        }
    }

    备注:

      * 查询方法的命名规范:

  • 相关阅读:
    Vue中v-for不绑定key会怎样
    关于Vuex可直接修改state问题
    不要完全相信Chrome控制台打印的信息
    Vue挂载元素的替换
    (转)openURL的使用方法
    iOS:将NSDate转换为当前时区时间
    OC中使用 static 、 extern、 const使用
    iOS: 正则表达式
    iOS:原生二维码扫描
    iOS:ABPeoplePickerNavigationController系统通讯录使用
  • 原文地址:https://www.cnblogs.com/linding/p/13703247.html
Copyright © 2011-2022 走看看