Spring Data ElasticSearch 使用

Spring Data ElasticSearch 使用

  1. Spring Data ElasticSearch entry
    1) Import Spring Data ElasticSearch coordinates
<?xml version="1.0" encoding="UTF-8"?>


4.0.0

<groupId>com.itheima</groupId>
<artifactId>itheima_elasticsearch_demo3</artifactId>
<version>1.0-SNAPSHOT</version>


<dependencies>
    <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-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>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.12</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>

2) Create a applicationContext.xml configuration file, namespace introduced elasticsearch

<?xml version="1.0" encoding="UTF-8"?>

<!-- 扫描Dao包,自动创建实例 -->
<elasticsearch:repositories base-package="com.itheima.dao"/>

<!-- 扫描Service包,创建Service的实体 -->
<context:component-scan base-package="com.itheima.service"/>

<!-- 配置elasticSearch的连接 -->
    <!-- 配置elasticSearch的连接 -->
<elasticsearch:transport-client id="client" cluster-nodes="localhost:9300" cluster-name="my-elasticsearch"/>


<!-- ElasticSearch模版对象 -->
<bean id="elasticsearchTemplate" class="org.springframework.data.elasticsearch.core.ElasticsearchTemplate">
    <constructor-arg name="client" ref="client"></constructor-arg>
</bean>

3) write entity Article

package com.itheima.domain;

public class Article {

private Integer id;
private String title;
private String content;
public Integer getId() {
    return id;
}
public void setId(Integer 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;
}
@Override
public String toString() {
    return "Article [id=" + id + ", title=" + title + ", content=" + content + "]";
}

}

4) preparation of Dao

package com.itheima.dao;

import com.itheima.domain.Article;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;

@Repository
public interface ArticleRepository extends ElasticsearchRepository<Article, Integer> {

}

5) the preparation of Service

package com.itheima.service;

import com.itheima.domain.Article;

public interface ArticleService {

public void save(Article article);

}

package com.itheima.service.impl;

import com.itheima.dao.ArticleRepository;
import com.itheima.domain.Article;
import com.itheima.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ArticleServiceImpl implements ArticleService {

@Autowired
private ArticleRepository articleRepository;

public void save(Article article) {
    articleRepository.save(article);
}

}

6) Configuration applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>

<!-- 扫描Dao包,自动创建实例 -->
<elasticsearch:repositories base-package="com.itheima.dao"/>

<!-- 扫描Service包,创建Service的实体 -->
<context:component-scan base-package="com.itheima.service"/>

<!-- 配置elasticSearch的连接 -->
    <!-- 配置elasticSearch的连接 -->
<elasticsearch:transport-client id="client" cluster-nodes="localhost:9300" cluster-name="my-elasticsearch"/>


<!-- ElasticSearch模版对象 -->
<bean id="elasticsearchTemplate" class="org.springframework.data.elasticsearch.core.ElasticsearchTemplate">
    <constructor-arg name="client" ref="client"></constructor-arg>
</bean>

7) Configure the entity

Based on the relationship between spring data elasticsearch annotation configuration index, mapping and entities

package com.itheima.domain;

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 Document Object (index information, document type)
@Document (indexName = "blog3", of the type = "Article This article was")
public class Article This article was {

//@Id 文档主键 唯一标识
@Id
//@Field 每个文档的字段配置(类型、是否分词、是否存储、分词器 )
@Field(store=true, index = false,type = FieldType.Integer)
private Integer id;
@Field(index=true,analyzer="ik_smart",store=true,searchAnalyzer="ik_smart",type = FieldType.text)
private String title;
@Field(index=true,analyzer="ik_smart",store=true,searchAnalyzer="ik_smart",type = FieldType.text)
private String content;
public Integer getId() {
    return id;
}
public void setId(Integer 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;
}
@Override
public String toString() {
    return "Article [id=" + id + ", title=" + title + ", content=" + content + "]";
}

}

Among them, notes explained as follows:
@Document (indexName = "blob3", of the type = "Article This article was"):
indexName: Index name (required)
of the type: the index type
@Id: uniquely identifies the primary key
@Field (index = true , Analyzer = "ik_smart", store = to true, searchAnalyzer = "ik_smart", of the type = FieldType.text)
index: whether to set word
analyzer: used when the memory word is
searchAnalyze: use when searching for the word breaker
store: whether the storage
type: type of data

8) Create a test class SpringDataESTest

package com.itheima.test;

import com.itheima.domain.Article;
import com.itheima.service.ArticleService;
import org.elasticsearch.client.transport.TransportClient;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations=“classpath:applicationContext.xml”)
public class SpringDataESTest {

@Autowired
private ArticleService articleService;

@Autowired
private TransportClient client;

@Autowired
private ElasticsearchTemplate elasticsearchTemplate;

/**创建索引和映射*/
@Test
public void createIndex(){
    elasticsearchTemplate.createIndex(Article.class);
    elasticsearchTemplate.putMapping(Article.class);
}

/**测试保存文档*/
@Test
public void saveArticle(){
    Article article = new Article();
    article.setId(100);
    article.setTitle("测试SpringData ElasticSearch");
    article.setContent("Spring Data ElasticSearch 基于 spring data API 简化 elasticSearch操作,将原始操作elasticSearch的客户端API 进行封装 \n" +
            "    Spring Data为Elasticsearch Elasticsearch项目提供集成搜索引擎");
    articleService.save(article);
}

}

2.Spring Data ElasticSearch common operation
CRUD Test Method

package com.itheima.service;

import com.itheima.domain.Article;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

public interface ArticleService {

//保存
public void save(Article article);
//删除
public void delete(Article article);
//查询全部
public Iterable<Article> findAll();
//分页查询
public Page<Article> findAll(Pageable pageable);

}

package com.itheima.service.impl;

import com.itheima.dao.ArticleRepository;
import com.itheima.domain.Article;
import com.itheima.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

@Service
public class ArticleServiceImpl implements ArticleService {

@Autowired
private ArticleRepository articleRepository;

public void save(Article article) {
    articleRepository.save(article);
}

public void delete(Article article) {
    articleRepository.delete(article);
}

public Iterable<Article> findAll() {
    Iterable<Article> iter = articleRepository.findAll();
    return iter;
}

public Page<Article> findAll(Pageable pageable) {
    return articleRepository.findAll(pageable);
}

}

package com.itheima.test;

import com.itheima.domain.Article;
import com.itheima.service.ArticleService;
import org.elasticsearch.client.transport.TransportClient;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations=“classpath:applicationContext.xml”)
public class SpringDataESTest {

@Autowired
private ArticleService articleService;

@Autowired
private TransportClient client;

@Autowired
private ElasticsearchTemplate elasticsearchTemplate;

/**创建索引和映射*/
@Test
public void createIndex(){
    elasticsearchTemplate.createIndex(Article.class);
    elasticsearchTemplate.putMapping(Article.class);
}

/**测试保存文档*/
@Test
public void saveArticle(){
    Article article = new Article();
    article.setId(100);
    article.setTitle("测试SpringData ElasticSearch");
    article.setContent("Spring Data ElasticSearch 基于 spring data API 简化 elasticSearch操作,将原始操作elasticSearch的客户端API 进行封装 \n" +
            "    Spring Data为Elasticsearch Elasticsearch项目提供集成搜索引擎");
    articleService.save(article);
}

/**测试保存*/
@Test
public void save(){
    Article article = new Article();
    article.setId(1001);
    article.setTitle("elasticSearch 3.0版本发布");
    article.setContent("ElasticSearch是一个基于Lucene的搜索服务器。它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口");
    articleService.save(article);
}

/**测试更新*/
@Test
public void update(){
    Article article = new Article();
    article.setId(1001);
    article.setTitle("elasticSearch 3.0版本发布...更新");
    article.setContent("ElasticSearch是一个基于Lucene的搜索服务器。它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口");
    articleService.save(article);
}

/**测试删除*/
@Test
public void delete(){
    Article article = new Article();
    article.setId(1001);
    articleService.delete(article);
}

/**批量插入*/
@Test
public void save100(){
    for(int i=1;i<=100;i++){
        Article article = new Article();
        article.setId(i);
        article.setTitle(i+"elasticSearch 3.0版本发布..,更新");
        article.setContent(i+"ElasticSearch是一个基于Lucene的搜索服务器。它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口");
        articleService.save(article);
    }
}

/**分页查询*/
@Test
public void findAllPage(){
    Pageable pageable = PageRequest.of(1,10);
    Page<Article> page = articleService.findAll(pageable);
    for(Article article:page.getContent()){
        System.out.println(article);
    }
}

}

Common Queries naming rules

Query method to test

Custom query methods
need to be named according to the naming SpringDataES.
If the paging information is not provided, the default tape tab 10 per data.
If the paging information should be added in a process parameter the Pageable
the Pageable PageRequest.of Pageable = (0, 15);
Note: set page information from the page 0 is the default start.

可以对搜索的内容先分词然后再进行查询。每个词之间都是and的关系。

1) dao layer implements

package com.itheima.dao;

import com.itheima.domain.Article;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import java.util.List;

interface ArticleRepository the extends ElasticsearchRepository public <Article This article was, Integer> {
// query by title
List

findByTitle (String for condition Condition);
// query based on the title (including pagination)
Page
findByTitle(String condition, Pageable pageable);
}

2) service layer implements

interface ArticleService {public
// query by title
List

findByTitle (String for condition Condition);
// query based on the title (including pagination)
Page
findByTitle(String condition, Pageable pageable);
}

package com.itheima.service.impl;

import com.itheima.dao.ArticleRepository;
import com.itheima.domain.Article;
import com.itheima.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ArticleServiceImpl implements ArticleService {

@Autowired
private ArticleRepository articleRepository;

public List<Article> findByTitle(String condition) {
    return articleRepository.findByTitle(condition);
}
public Page<Article> findByTitle(String condition, Pageable pageable) {
    return articleRepository.findByTitle(condition,pageable);
}

}

3) test code

package com.itheima.test;

import com.itheima.domain.Article;
import com.itheima.service.ArticleService;
import org.elasticsearch.client.transport.TransportClient;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations=“classpath:applicationContext.xml”)
public class SpringDataESTest {

@Autowired
private ArticleService articleService;

@Autowired
private TransportClient client;

@Autowired
private ElasticsearchTemplate elasticsearchTemplate;

/**条件查询*/
@Test
public void findByTitle(){
    String condition = "版本";
    List<Article> articleList = articleService.findByTitle(condition);
    for(Article article:articleList){
        System.out.println(article);
    }
}

/**条件分页查询*/
@Test
public void findByTitlePage(){
    String condition = "版本";
    Pageable pageable = PageRequest.of(2,10);
    Page<Article> page = articleService.findByTitle(condition,pageable);
    for(Article article:page.getContent()){
        System.out.println(article);
    }
}

}

Use Elasticsearch native query object query.

Use native search criteria
NativeSearchQuery objects.
Usage:
1) Create a NativeSearchQuery objects
set query conditions, QueryBuilder objects
2) object to perform a query using ElasticSearchTemplate
3) take Results

@Test
public void findByNativeQuery () {
// create a SearchQuery objects
SearchQuery searchQuery new new NativeSearchQueryBuilder = ()
// set query conditions, may be used herein to create various inquiry QueryBuilders
.withQuery (QueryBuilders.queryStringQuery ( "no data on the backup node" ) .defaultField ( "title"))
// You can also set the pagination information
.withPageable (PageRequest.of (1, 5))
// create SearchQuery objects
.build ();

    //使用模板对象执行查询
    elasticsearchTemplate.queryForList(searchQuery, Article.class)
            .forEach(a-> System.out.println(a));
}

Lessons Learned

SpringDataElasticSearch
1, engineering structures
1) to create a java project.
2) the relevant jar package is added to the project. If maven project will add coordinates.
3) Create a spring configuration file
1, configuration elasticsearch: Transport-Client
2, elasticsearch: Repositories: bag scanner, scan DAO
3, configuration elasticsearchTemplate object is a bean
2, library management index
1, create an Entity class, in fact, is a JavaBean (pojo) mapped to a Document
need to add some notes to mark.
2, create a Dao, is an interface, the interface needs to inherit ElasticSearchRepository.
3, write test code.

3, to create an index
to create indexes directly createIndex method ElasticsearchTemplate object, and configure mappings.
4, add, update document
1) Create an Article object
2) add documents to the index database using ArticleRepository object.
5, delete documents
directly ArticleRepository object deleteById method delete.
6, the index database queries
directly with the query method ArticleRepository object.
7, the custom query methods
need to be named according to the naming SpringDataES.
If the paging information is not provided, the default tape tab 10 per data.
If the paging information should be added in a process parameter the Pageable
the Pageable PageRequest.of Pageable = (0, 15);
Note: set page information from the page 0 is the default start.

可以对搜索的内容先分词然后再进行查询。每个词之间都是and的关系。

8, using the native search criteria
NativeSearchQuery objects.
Usage:
1) Create a NativeSearchQuery objects
set query conditions, QueryBuilder objects
2) object to perform a query using ElasticSearchTemplate
3) take Results

Attached using the Java Client Management ES Summary

First, the use of Java Client Management ES
1, create an index library
steps:
1) Create a Java project
2) add a jar package, add coordinates maven of
3) preparation of test method implementation creates an index database
1. Create a Settings object, the equivalent of a configuration information. The main name of the cluster configuration.
2. Create a client Client object
3, using the client object creates an index database
4, close the client object
2, using the Java client settings Mappings
steps:
1) create a Settings object
2) create a Client object
3) create a mapping information should be a json data, can be a string, an object may be XContextBuilder
4) using the mapping information to the client sends the server es
5) Close the client object
3, add documents
steps:
1) Create a Settings object
2) creates a Client object
3) create a document object, creating a json string format, or use XContentBuilder
4) using the Client Object bar add documents to the index database
5) closed Client
4, the document added a second way
to create a class pojo
use tools to pojo converted into a string json
The written document index database

Second, the client implementation using es search
1, search according to id
the QueryBuilder QueryBuilder = QueryBuilders.idsQuery () addIds ( "1", "2");.
2, according Term query (keyword)
the QueryBuilder QueryBuilders.termQuery QueryBuilder = ( " title "," North ");
. 3, the QueryString query (query) with the analysis
QueryBuilder queryBuilder = QueryBuilders.queryStringQuery (" speed and passion ")
; .defaultField (" title ")
querying step:
Create a Client object 1)
2 ) to create a query object, you can create objects using QueryBuilders QueryBuilder tools.
3) using the client execute the query
4) get the results of the query.
5) Take the total number of records query results
6) takes the query result
7) closed client
. 4, the paging process
in the client object before executing the query, set page information.
And then execute the query
// execute query
SearchResponse SearchResponse = client.prepareSearch ( "index_hello")
.setTypes ( "Article This article was")
.setQuery (QueryBuilder)
// set page information
.setFrom (0)
// number of lines per page of
.setSize (. 5)
.get ();
tab to set two values, one from, size
from: starting line number, starting from 0.
size: the number of records per page
5, highlighting the query results
(1) to highlight the configuration
1) setting field highlighted
2) disposed prefix highlighted
3) disposed suffix highlighted
(2) client object before executing the query, set the information highlighted.
The results can be taken from the results highlight (3) through the results list.

Guess you like

Origin blog.csdn.net/qq_21683643/article/details/94553874