ElasticSearch基本操作——基于Java实现(SpringDataElasticSearch)

Posted QQ:359855043

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ElasticSearch基本操作——基于Java实现(SpringDataElasticSearch)相关的知识,希望对你有一定的参考价值。

一.创建工程、导入坐标

1.选择Next

 

 2.填写名称、选择位置、填写公司或组织、选择Finish

 

 3.导入坐标

<?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>cn.lb</groupId>
    <artifactId>elasticsearch</artifactId>
    <version>1.0.0.0-SNAPSHOT</version>
    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>6.3.1</version>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>transport</artifactId>
            <version>6.3.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-to-slf4j</artifactId>
            <version>2.9.1</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.24</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <version>1.7.21</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.8.1</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.8.1</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.8.1</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-elasticsearch</artifactId>
            <version>3.0.5.RELEASE</version>
            <exclusions>
                <exclusion>
                    <groupId>org.elasticsearch.plugin</groupId>
                    <artifactId>transport-netty4-client</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.0.4.RELEASE</version>
        </dependency>
    </dependencies>
</project>

 4.创建实体类:Article

package cn.lb.es.entity;

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;

@Document(indexName = "index_blog",type="article")
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;

    @Override
    public String toString() {
        return "Article{" +
                "id=" + id +
                ", title=\'" + title + \'\\\'\' +
                ", content=\'" + content + \'\\\'\' +
                \'}\';
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }
}

5.创建接口

package cn.lb.es.repositories;

import cn.lb.es.entity.Article;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.data.repository.NoRepositoryBean;

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);
}

6.添加配置

<?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
        http://www.springframework.org/schema/data/elasticsearch/spring-elasticsearch-1.0.xsd
        ">
    <!--elastic客户对象的配置-->
    <elasticsearch:transport-client id="esClient" cluster-name="my-elasticsearch"
                                    cluster-nodes="127.0.0.1:9300,127.0.0.1:9301,127.0.0.1:9302"/>
    <!--配置包扫描器,扫描dao的接口-->
    <elasticsearch:repositories base-package="cn.lb.es.repositories"/>
    <!---->
    <bean id="elasticsearchTemplate" class="org.springframework.data.elasticsearch.core.ElasticsearchTemplate">
        <constructor-arg name="client" ref="esClient"/>
    </bean>

</beans>

7.测试

import cn.lb.es.entity.Article;
import cn.lb.es.repositories.ArticleRepository;
import org.elasticsearch.index.query.QueryBuilder;
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.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.web.PageableDefault;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class SpringDataElasticSearchTest {

    @Autowired
    private ArticleRepository articleRepositrory;

    @Autowired
    private ElasticsearchTemplate template;


    @Test
    public  void createIndex() throws  Exception{
        template.createIndex(Article.class);
    }

    @Test
    public  void addDocument() throws Exception
    {
      
            Article article =new Article();
            article.setId(i);
            article.setTitle("IntelliJ IDEA 编译Java程序出现 \'Error:java: 无效的源发行版: 9\' 的解决方案");
            article.setContent("最新安装的IntelliJ IDEA 2018.1编译器,创建Java Project,并选择之前安装好的Eclipse配置的JDK,如图所示:");
            articleRepositrory.save(article);
        
    }

    @Test
    public void deleteDocumentId() throws  Exception
    {
        articleRepositrory.deleteById(2l);

        //articleRepositrory.deleteAll();
    }

    @Test
    public  void findByTitle() throws Exception
    {
        List<Article> list=articleRepositrory.findByTitle("9");
        list.stream().forEach(a-> System.out.println(a));
    }

    @Test
    public  void findByTitleOrContent() throws Exception
    {
        Pageable pageable=PageRequest.of(0,15);
        List<Article> list = articleRepositrory.findByTitleOrContent("9", "n", pageable);
        list.forEach(a-> System.out.println(a));
    }

    @Test
    public void nativeSearchQuery() throws Exception
    {
        NativeSearchQuery query=new NativeSearchQueryBuilder()
                .withQuery(QueryBuilders.queryStringQuery("Java是最好的语言").defaultField(
                        "title"
                )).withPageable(PageRequest.of(0,15)).build();

        List<Article> list = template.queryForList(query, Article.class);
        list.forEach(a-> System.out.println(a));
    }
}

 

以上是关于ElasticSearch基本操作——基于Java实现(SpringDataElasticSearch)的主要内容,如果未能解决你的问题,请参考以下文章

elasticsearch 基本概念

ElasticSearch JavaAPI(java操作)

ElasticSearch基本概念

索引 - ElasticSearch基本使用

五万字长文详解SpringBoot 操作 ElasticSearch

elasticsearch可视化工具