Elasticsearch 安装
添加小编微信进入java学习交流群,小编微信:372787553,备注进群
具体安装步骤网上很多,大家可以借鉴一下;
关于分词插件的安装可以执行一下命令:
拼音插件
./bin/elasticsearch-plugin install https://github.com/medcl/elasticsearch-analysis-pinyin/releases/download/v6.1.1/elasticsearch-analysis-pinyin-6.1.1.zip
中文插件
./bin/elasticsearch-plugin install https://github.com/medcl/elasticsearch-analysis-ik/releases/download/v6.1.1/elasticsearch-analysis-ik-6.1.1.zip
如不行执行在线下载,也可以离线下载
放在安装 elasticsearch 下plugins内即可
Boot + Es
1.相关依赖
本文用的是boot2.0.2,这里也配置了数据库
<?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>
<parent>
<groupId>com.javayh</groupId>
<artifactId>javayh-oauth2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../</relativePath><!-- lookup parent from repository -->
</parent>
<groupId>com.javayh</groupId>
<artifactId>javayh-elasticsearch</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>javayh-elasticsearch</name>
<packaging>jar</packaging>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>com.javayh</groupId>
<artifactId>javayh-commons</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>net.java.dev.jna</groupId>
<artifactId>jna</artifactId>
<version>3.0.9</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2.配置文件
server:
port: 8087
spring:
application:
name: javayh-elastic
data:
elasticsearch:
repositories:
enabled: true
cluster-name: elasticsearch
cluster-nodes: 127.0.0.1:9300
properties:
path:
logs: ./elasticsearch/log
data: ./elasticsearch/data
local: true
datasource:
url: jdbc:mysql://localhost:3306/test?characterEncoding=UTF-8&useUnicode=true&useSSL=false
username: root
password: 1219320
driver-class-name: com.mysql.jdbc.Driver
mybatis:
dao-locations: classpath:dao/*.mapper
type-aliases-package: com.javayh.entity
eureka:
instance:
prefer-ip-address: true
instance-id: ${spring.cloud.client.ip-address}:${server.port}
client:
service-url:
defaultZone: http://localhost:8090/eureka/
3.实体映射
@Data
@Document(indexName = "javayh",type = "sys_es")
public class EsEntiy implements Serializable {
@Id
private String esId;
@Field(type = FieldType.Text)
private String esIndex;
@Field(type = FieldType.Text)
private String esType;
@Field(type = FieldType.Text)
private String esCode;
}
4.Repository JPA的封装
@Repository
public interface EsRepository extends ElasticsearchRepository<EsEntiy,String> {
}
5.EsService
这里包含了新增、普通的查询、模糊查询、高亮检索
@Service
public class EsService {
@Autowired
private EsRepository esRepository;
@Autowired
private ElasticsearchTemplate elasticsearchTemplate;
/**
* 保存
* @param esEntiy
* @return
*/
public EsEntiy save(EsEntiy esEntiy){
if (StringUtils.isEmpty(esEntiy.getEsCode()))
throw new BaseException("eslasticsearch code is null");
esEntiy.setEsId(UuidUtils.getUuid());
return esRepository.save(esEntiy);
}
/**
* 查询
* @param code
* @return
*/
public EsEntiy findbyEs(String code){
Optional<EsEntiy> byId = esRepository.findById(code);
return byId.get();
}
/**
* 删除
* @param id
* @return
*/
public int delete(String id){
if(StringUtils.isEmpty(id))
esRepository.deleteById(id);
EsEntiy esEntiy = esRepository.findById(id).get();
return esEntiy == null ? 0: 1 ;
}
/**
* matchQuery : 单个字段查询
* matchAllQuery : 匹配所有
* multiMatchQuery : 多个字段匹配某一个值
* wildcardQuery : 模糊查询
* boost : 设置权重,数值越大权重越大
* 混合搜索
* @param content
* @return
*/
public Page<EsEntiy> querySearch(String content){
DisMaxQueryBuilder disMaxQueryBuilder = QueryBuilders.disMaxQuery();
QueryBuilder ikTypeQuery = QueryBuilders.matchQuery("esType", content).boost(2f);
QueryBuilder pinyinTypeQuery = QueryBuilders.matchQuery("esType.pinyin", content);
QueryBuilder ikCodeQuery = QueryBuilders.matchQuery("esCode", content).boost(2f);
QueryBuilder pinyinCodeQuery = QueryBuilders.matchQuery("esCode.pinyin", content);
QueryBuilder wildcardCodeQuery = QueryBuilders.wildcardQuery("esCode", content);
QueryBuilder multiCodeQuery = QueryBuilders.multiMatchQuery(content,"esType","esCode");
disMaxQueryBuilder.add(ikTypeQuery);
disMaxQueryBuilder.add(pinyinTypeQuery);
disMaxQueryBuilder.add(ikCodeQuery);
disMaxQueryBuilder.add(pinyinCodeQuery);
disMaxQueryBuilder.add(wildcardCodeQuery);
disMaxQueryBuilder.add(multiCodeQuery);
SearchQuery searchQuery = new NativeSearchQueryBuilder()
.withQuery(disMaxQueryBuilder).build();
Page<EsEntiy> search = esRepository.search(searchQuery);
return search;
}
/**
* 高亮检索
* @param type
* @return
*/
public AggregatedPage<EsEntiy> querySearchType(String type){
DisMaxQueryBuilder disMaxQueryBuilder = QueryBuilders.disMaxQuery();
QueryBuilder ikTypeQuery = QueryBuilders.wildcardQuery("esType", type).boost(2f);
QueryBuilder ikCodeQuery = QueryBuilders.wildcardQuery("esCode", type).boost(2f);
List<String> highlightFields = new ArrayList<String>();
highlightFields.add("esType");
highlightFields.add("esCode");
HighlightBuilder.Field[] fields = new HighlightBuilder.Field[highlightFields.size()];
for (int x = 0; x < highlightFields.size(); x++) {
fields[x] = new HighlightBuilder.Field(highlightFields.get(x)).preTags(EsHighlight.HIGH_LIGHT_START_TAG)
.postTags(EsHighlight.HIGH_LIGHT_END_TAG);
}
disMaxQueryBuilder.add(ikTypeQuery);
disMaxQueryBuilder.add(ikCodeQuery);
SearchQuery searchQuery = new NativeSearchQueryBuilder()
.withQuery(disMaxQueryBuilder)
.withHighlightFields(fields)
//.withPageable(PageRequest.of(1, 10))
.build();
//不需要高亮就直接分页返回
//Page<EsEntiy> esEntiys = esRepository.search(searchQuery);
//高亮显示
AggregatedPage<EsEntiy> esEntiys = elasticsearchTemplate.queryForPage(searchQuery, EsEntiy.class, new SearchResultMapper() {
@Override
public <T> AggregatedPage<T> mapResults(SearchResponse searchResponse, Class<T> aClass, Pageable pageable) {
pageable = PageRequest.of(1, 10);
List<EsEntiy> chunk = new ArrayList<>();
for (SearchHit searchHit : searchResponse.getHits()) {
if (searchResponse.getHits().getHits().length <= 0) {
return null;
}
EsEntiy esEntiy = new EsEntiy();
esEntiy.setEsId(searchHit.getId());
esEntiy.setEsIndex(searchHit.getIndex());
//name or memoe
HighlightField code = searchHit.getHighlightFields().get("esCode");
if (code != null) {
esEntiy.setEsCode(code.fragments()[0].toString());
} else {
Object esCode = searchHit.getSourceAsMap().get("esCode");
if(esCode == null)
esEntiy.setEsCode("");
else
esEntiy.setEsCode(esCode.toString());
}
HighlightField type = searchHit.getHighlightFields().get("esType");
if (type != null) {
esEntiy.setEsType(type.fragments()[0].toString());
}else {
Object esType = searchHit.getSourceAsMap().get("esType");
if(esType == null )
esEntiy.setEsType("");
else
esEntiy.setEsType(esType.toString());
}
chunk.add(esEntiy);
}
if (chunk.size() > 0) {
return new AggregatedPageImpl<T>((List<T>) chunk);
}
return null;
}
});
return esEntiys;
}
}
6. 高亮配置
承接上边的代码
public interface EsHighlight {
/**
* 高亮显示 - 开始标签
*/
String HIGH_LIGHT_START_TAG = "<javayh>";
/**
* 高亮显示 - 结束标签
*/
String HIGH_LIGHT_END_TAG = "</javayh>";
/**
* 索引名称
*/
class INDEX_NAME {
/**
* 游记
*/
public static final String TRAVEL = "travel";
}
效果展示
1.新增
我们可以通过es-head进行查看
2. 高亮检索
可以看出已经将我们的搜索条件“测”,进行了高亮显示
boot2.X整合es已经完成,希望对看到的朋友有所帮助!
如有疑问可以添加小编微信:372787553,互相交流!
关注 Java有货领取更多资料
联系小编。微信:372787553,带您进群互相学习
左侧小编微信,右侧获取免费资料
- SpringCloud 自定义封装架构https://github.com/yanghaiji/javayh-platform
- Java 设计模式学习代码 https://github.com/yanghaiji/design-pattern
- SpringCloud学习代码: https://github.com/yanghaiji/javayh-cloud
- AlibabaCloud学习代码:https://github.com/yanghaiji/javayh-cloud-nacos
- SpringBoot+Mybatis 多数据源切换:https://github.com/yanghaiji/javayh-boot-data-soure
- Redis、Mongo、Rabbitmq、Kafka学习代码: https://github.com/yanghaiji/javayh-middleware
- SpringBoot+SpringSecurity实现自定义登录学习代码:https://github.com/yanghaiji/javayh-distribution