Spring Data Elasticsearch操作

直接上代码

1、依赖

<?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>com.itheima</groupId>
    <artifactId>springdata-elasticsearch</artifactId>
    <version>1.0-SNAPSHOT</version>
    <properties>
        <maven.compiler.source>1.9</maven.compiler.source>
        <maven.compiler.target>1.9</maven.compiler.target>
    </properties>
    <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>

</project>

2、实体类

package com.itheima.es.entity;

import  com.itheima.es.entity.UserList;

import java.util.List;

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 = "blog22", type = "article")
public class Article {
    @Id
    @Field(type = FieldType.Long, store = true)
    private long id;
    @Field(type = FieldType.text, store = true, analyzer = "standard")
    private String title;
    @Field(type = FieldType.text, store = true, analyzer = "standard")
    private String content;
    @Field(type=FieldType.Object)
    private UserList userInfo;
    @Field(type=FieldType.Nested)
    private List<UserList> userList;

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

	public UserList getUserInfo() {
		return userInfo;
	}

	public void setUserInfo(UserList userInfo) {
		this.userInfo = userInfo;
	}

	public List<UserList> getUserList() {
		return userList;
	}

	public void setUserList(List<UserList> userList) {
		this.userList = userList;
	}

	@Override
	public String toString() {
		return "Article [id=" + id + ", title=" + title + ", content=" + content + ", userInfo=" + userInfo
				+ ", userList=" + userList + "]";
	}
    

}
package com.itheima.es.entity;

import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;

public class UserList {
	
	@Field(type = FieldType.text, store = true, analyzer = "standard")
	private String userName;
	@Field(type = FieldType.text, store = true, analyzer = "standard")
	private String sexName;

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getSexName() {
		return sexName;
	}

	public void setSexName(String sexName) {
		this.sexName = sexName;
	}

	@Override
	public String toString() {
		return "UserList [userName=" + userName + ", sexName=" + sexName + "]";
	}
	
	
	

}

3、集成的接口,好像没用

package com.itheima.es.repositories;

import com.itheima.es.entity.Article;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;

import java.util.List;

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

 

4、测试类

import com.itheima.es.entity.Article;
import com.itheima.es.entity.UserList;
import com.itheima.es.repositories.ArticleRepository;

import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
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.PageImpl;
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.SearchResultMapper;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.aggregation.impl.AggregatedPageImpl;
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.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
public class SpringDataElasticSearchTest {
/**
 * 注意点Spring-data-ElasticSearch版本支持ElasticSearch5.X版本
 */
    @Autowired
    private ArticleRepository articleRepository;
    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    @Test
    public void createIndex() throws Exception {
        //创建索引,并配置映射关系
    	elasticsearchTemplate.createIndex(Article.class);
        //配置映射关系
//    	elasticsearchTemplate.putMapping(Article.class);
    }
    
 
    @Test
    public void addDocument() throws Exception {
        for (int i = 21; i <= 23; i++) {
            //创建一个Article对象
            Article article = new Article();
            article.setId(i);
            article.setTitle("集群健康值"+i);
            article.setContent("盛会再携手—各国政要高度评价东博会和商务与投资峰会");
            UserList userInfo = new UserList();
            userInfo.setUserName("张"+i);
            userInfo.setSexName("男");
            
            UserList userInfo1 = new UserList();
            
            userInfo1.setUserName("李"+i);
            userInfo1.setSexName("女"+i);
            List<UserList> list = new ArrayList<UserList>();
            list.add(userInfo);
            list.add(userInfo1);
            article.setUserInfo(userInfo);
            article.setUserList(list);
            //把文档写入索引库
            articleRepository.save(article);

        }
    }
    @Test
    public void deleteDocumentById() throws Exception {
//        articleRepository.deleteById(11l);
        //全部删除
        articleRepository.deleteAll();
    }

    @Test
    public void findAll() throws Exception {
        Iterable<Article> articles = articleRepository.findAll();
        articles.forEach(a-> System.out.println(a));
    }
    @Test
    public void testFindById() throws Exception {
        Optional<Article> optional = articleRepository.findById(12l);
        Article article = optional.get();
        System.out.println(article);
    }

    @Test
    public void testFindByTitle() throws Exception {
        List<Article> list = articleRepository.findByTitle("maven是一个工程构建工具");
        list.stream().forEach(a-> System.out.println(a));
    }

    @Test
    public void testFindByTitleOrContent() throws Exception {
        Pageable pageable = PageRequest.of(1, 15);
        articleRepository.findByTitleOrContent("maven", "商务与投资", pageable)
                .forEach(a-> System.out.println(a));
    }

    @Test
    public void testNativeSearchQuery() throws Exception {
        //创建一个查询对象
        NativeSearchQuery query = new NativeSearchQueryBuilder()
                .withQuery(QueryBuilders.queryStringQuery("maven是一个工程构建工具").defaultField("title"))
                .withPageable(PageRequest.of(0, 15))
                .build();
        //执行查询
        List<Article> articleList = elasticsearchTemplate.queryForList(query, Article.class);
        articleList.forEach(a-> System.out.println(a));
    }
    
    /**
     * 高亮获取
     */
    @Test
	public void highLightQueryTest() {
    	
    	//另外一种方式https://segmentfault.com/a/1190000017324038?utm_source=tag-newest
		String field = "title";
		String searchMessage = "健康值";
		List<Article> articleList = highLigthQuery(field, searchMessage);
		for(Article article:articleList) {
			System.out.println(article.toString());
		}
		
	}
    
    public List<Article> highLigthQuery(String field, String searchMessage) {
		NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
				.withQuery(QueryBuilders.queryStringQuery(searchMessage).defaultField(field))
				.withHighlightFields(new HighlightBuilder.Field(field)).build();
		AggregatedPage<Article> page = elasticsearchTemplate.queryForPage(searchQuery, Article.class, new SearchResultMapper() {
 
			@Override
			public <T> AggregatedPage<T> mapResults(SearchResponse response, Class<T> clazz, Pageable pageable) {
				ArrayList<Article> articles = new ArrayList<Article>();
				SearchHits hits = response.getHits();
				for (SearchHit searchHit : hits) {
					if (hits.getHits().length <= 0) {
						return null;
					}
					Article article = new Article();
					String highLightMessage = searchHit.getHighlightFields().get(field).fragments()[0].toString();
					article.setId(Integer.parseInt(searchHit.getId()));
					article.setTitle(String.valueOf(searchHit.getSource().get("title")));
					article.setContent(String.valueOf(searchHit.getSource().get("content")));
					Map<String,String> userMap = (Map<String, String>) searchHit.getSource().get("userInfo");
					UserList userinfo = new UserList();
					userinfo.setSexName(userMap.get("sexName"));
					userinfo.setUserName(userMap.get("userName"));
					article.setUserInfo(userinfo);
					
					List<UserList> userList = new ArrayList<UserList>();
					List<Map<String,String>>  userMapList = (List<Map<String,String>> ) searchHit.getSource().get("userList");
					for(Map<String,String> userInfoMap:userMapList) {
						UserList user = new UserList();
						user.setSexName(userMap.get("sexName"));
						user.setUserName(userMap.get("userName"));
						userList.add(user);
					}
					article.setUserList(userList);
					// 反射调用set方法将高亮内容设置进去
					try {
						String setMethodName = parSetName(field);
						Class<? extends Article> articleClazz = article.getClass();
						Method setMethod = articleClazz.getMethod(setMethodName, String.class);
						setMethod.invoke(article, highLightMessage);
					} catch (Exception e) {
						e.printStackTrace();
					}
					articles.add(article);
				}
				if (articles.size() > 0) {
					return new AggregatedPageImpl<T>((List<T>) articles);
				}
				return null;
			}
		});
		List<Article> articleList = page.getContent();
		return articleList;
	}
    

	/**
	 * 拼接在某属性的 set方法
	 * 
	 * @param fieldName
	 * @return String
	 */
	private static String parSetName(String fieldName) {
		if (null == fieldName || "".equals(fieldName)) {
			return null;
		}
		int startIndex = 0;
		if (fieldName.charAt(0) == '_')
			startIndex = 1;
		return "set" + fieldName.substring(startIndex, startIndex + 1).toUpperCase()
				+ fieldName.substring(startIndex + 1);
	}




    



}

5、

<?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-es"
                                    cluster-nodes="192.168.2.171:9300"/>
    <!--配置包扫描器,扫描dao的接口-->
    <elasticsearch:repositories base-package="com.itheima.es.repositories"/>
    <!---->
    <bean id="elasticsearchTemplate" class="org.springframework.data.elasticsearch.core.ElasticsearchTemplate">
        <constructor-arg name="client" ref="esClient"/>
    </bean>

</beans>

配置文件

 

 

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值