前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Spring和Elasticsearch全文搜索整合详解

Spring和Elasticsearch全文搜索整合详解

作者头像
品茗IT
发布2019-09-12 09:46:29
2.4K0
发布2019-09-12 09:46:29
举报
文章被收录于专栏:品茗IT品茗IT

Spring和Elasticsearch全文搜索整合详解

一、概述

ElasticSearch是一个基于Lucene的搜索服务器。它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口。Elasticsearch是用Java开发的,并作为Apache许可条款下的开放源码发布,是当前流行的企业级搜索引擎。

ES是ElasticSearch的缩写;

ELK是三个开源软件的缩写,分别表示:Elasticsearch , Logstash, Kibana , 它们都是开源软件。

一般公司都是用ELK做日志分析,社区搜索之类的,很少单独使用ElasticSearch。但是单独使用ElasticSearch也很广泛,没有ELK的时候都是这样玩的。

比如我的社区网站(https://www.pomit.cn)就用了ElasticSearch做社区搜索,一开始做搜索的时候,曾有三种方案:

  • Mysql的全文搜索,据说很慢,而且我的mysql版本也不支持中文,还要升级。
  • 搜索引擎的支持,搜索引擎可以传入keyword、site对网站的某个网页做搜索,但是依赖于搜索引擎的收录情况。特别是百度渣渣,求它收录都难,必应还是蛮快的。但是都不够快。
  • ElasticSearch做社区搜索,需要安装ElasticSearch。用了一段时间,感觉还可以。

**如果大家正在寻找一个java的学习环境,或者在开发中遇到困难,可以<a

href="https://jq.qq.com/?_wv=1027&k=52sgH1J"

target="_blank">

加入我们的java学习圈,点击即可加入

</a>

,共同学习,节约学习时间,减少很多在学习中遇到的难题。**

二、环境配置

本文假设你已经引入Spring必备的一切了,已经是个Spring项目了,如果不会搭建,可以打开这篇文章看一看《Spring和Spring Mvc 5整合详解》

2.1 maven依赖

使用elasticsearch需要引入spring-data-elasticsearch,而且要保证版本和安装的elasticsearch对应。

代码语言:javascript
复制
<?xml version="1.0"?>
<project
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
	xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>cn.pomit</groupId>
		<artifactId>SpringWork</artifactId>
		<version>0.0.1-SNAPSHOT</version>
	</parent>
	<artifactId>Elasticsearch</artifactId>
	<packaging>jar</packaging>
	<name>Elasticsearch</name>
	<url>http://maven.apache.org</url>
	<properties>
	    <!-- redis 版本 -->
	    <elasticsearch.version>3.1.6.RELEASE</elasticsearch.version>
	    
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
		</dependency>
		<dependency>
		    <groupId>org.springframework.data</groupId>
		    <artifactId>spring-data-elasticsearch</artifactId>
		    <version>${elasticsearch.version}</version>
		</dependency>
		<dependency>
		    <groupId>org.springframework.data</groupId>
		    <artifactId>spring-data-commons</artifactId>
		    <version>2.1.6.RELEASE</version>
		</dependency>
	</dependencies>
	<build>
		<finalName>Elasticsearch</finalName>
	</build>
</project>

父模块可以在https://www.pomit.cn/spring/SpringWork/pom.xml获取。

2.2 Spring配置

需要配置elasticsearchTemplate和elasticsearch:transport-client。

代码语言:javascript
复制
<?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:elasticsearch="http://www.springframework.org/schema/data/elasticsearch"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                            http://www.springframework.org/schema/data/elasticsearch http://www.springframework.org/schema/data/elasticsearch/spring-elasticsearch.xsd
                            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
   	
   	<bean id="annotationPropertyConfigurerElasticsearch"
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="order" value="1" />
		<property name="ignoreUnresolvablePlaceholders" value="true" />
		<property name="locations">
			<list>
				<value>classpath:elasticsearch.properties</value>
			</list>
		</property>
	</bean>
   
    <elasticsearch:transport-client id="client"
        cluster-nodes="${elasticsearch.cluster-nodes}" cluster-name="${elasticsearch.cluster-name}" />

    <bean name="elasticsearchTemplate"
        class="org.springframework.data.elasticsearch.core.ElasticsearchTemplate">
        <constructor-arg ref="client" />
    </bean>
    
     <elasticsearch:repositories base-package="cn.pomit.springwork.elasticsearch.dao" />
</beans>

elasticsearch.properties中存放elasticsearch的地址端口信息。

elasticsearch.properties:

代码语言:javascript
复制
elasticsearch.cluster-name=elasticsearch
elasticsearch.cluster-nodes=127.0.0.1:9300

三、Elasticsearch访问数据层

我们直接使用Spring-data-elasticsearch, 一切都会变的特别简单。Spring-data-elasticsearch支持快速查询,也支持@Query之定义查询,要注意它的写法,和elasticsearch原生写法略有不同。

QuestionElasticsearchRepository :

代码语言:javascript
复制
package cn.pomit.springwork.elasticsearch.dao;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.annotations.Query;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;

import cn.pomit.springwork.elasticsearch.domain.FQuestionElasticssearch;

public interface QuestionElasticsearchRepository extends ElasticsearchRepository<FQuestionElasticssearch, Long> {

	Page<FQuestionElasticssearch> findByCatory(String catory, Pageable pageable);

	@Query("{ \"bool\":{ \"must\":[ { \"multi_match\": { \"query\": \"?0\", \"type\": \"most_fields\", \"fields\": [ \"title\", \"content\" ] } }, { \"match\": { \"catory\": \"?1\" } } ] } } ")
	Page<FQuestionElasticssearch> searchByKeyWordsAndCatory(String keyword, String catory, Pageable pageable);

}

这个写法和Spring-data-jpa基本上一样,应该说Spring-data系列的写法都是类同的。

注意,FQuestionElasticssearch实体需要加上@Document注解指明Elasticssearch中的index和type。

四、测试Elasticssearch

我们定义一个service和web接口来做测试。

QuestionElasticsearchService:

代码语言:javascript
复制
package cn.pomit.springwork.elasticsearch.service;

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.stereotype.Service;
import org.springframework.util.StringUtils;

import cn.pomit.springwork.elasticsearch.dao.QuestionElasticsearchRepository;
import cn.pomit.springwork.elasticsearch.domain.FQuestionElasticssearch;

@Service
public class QuestionElasticsearchService {
	@Autowired
	QuestionElasticsearchRepository questionElasticsearchRepository;

	public Page<FQuestionElasticssearch> pageByOpenAndCatory(Integer page, Integer size, String catory,
			String keyWord) {
		Pageable pageable = PageRequest.of(page, size);
		if (StringUtils.isEmpty(keyWord)) {
			return questionElasticsearchRepository.findByCatory(catory, pageable);

		} else {
			return questionElasticsearchRepository.searchByKeyWordsAndCatory(keyWord, catory, pageable);

		}
	}
}

ElasticsearchRest:

代码语言:javascript
复制
package cn.pomit.springwork.elasticsearch.web;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import cn.pomit.springwork.elasticsearch.domain.FQuestionElasticssearch;
import cn.pomit.springwork.elasticsearch.service.QuestionElasticsearchService;

@RestController
@RequestMapping("/elsearch")
public class ElasticsearchRest {

	@Autowired
	QuestionElasticsearchService questionElasticsearchService;

	@RequestMapping(value = "/test", method = { RequestMethod.GET })
	public List<FQuestionElasticssearch> test(@RequestParam(value = "value", required = false) String value) {
		return questionElasticsearchService.pageByOpenAndCatory(0, 10, "Spring专题", value).getContent();
	}
}

五、过程中用到的实体

FQuestionElasticssearch:

代码语言:javascript
复制
package cn.pomit.springwork.elasticsearch.domain;

import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;

@Document(indexName = "pomit", type = "issue", createIndex = false)
public class FQuestionElasticssearch {
	@Id
	private Long id;
	private String title;
	private String catory;
	private String content;

	public FQuestionElasticssearch() {
	}

	public Long getId() {
		return id;
	}

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

	public void setCatory(String catory) {
		this.catory = catory;
	}

	public String getCatory() {
		return catory;
	}
	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;
	}

}
本文参与?腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019-07-08 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客?前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与?腾讯云自媒体同步曝光计划? ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Spring和Elasticsearch全文搜索整合详解
  • 一、概述
  • 二、环境配置
    • 2.1 maven依赖
      • 2.2 Spring配置
      • 三、Elasticsearch访问数据层
      • 四、测试Elasticssearch
      • 五、过程中用到的实体
      相关产品与服务
      Elasticsearch Service
      腾讯云 Elasticsearch Service(ES)是云端全托管海量数据检索分析服务,拥有高性能自研内核,集成X-Pack。ES 支持通过自治索引、存算分离、集群巡检等特性轻松管理集群,也支持免运维、自动弹性、按需使用的 Serverless 模式。使用 ES 您可以高效构建信息检索、日志分析、运维监控等服务,它独特的向量检索还可助您构建基于语义、图像的AI深度应用。
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
      http://www.vxiaotou.com