elasticsearch版本_SpringBoot 集成 Elasticsearch

(给ImportNew加星标,提高Java技能)

作者:废物大师兄

www.cnblogs.com/cjsblog/p/9756978.html 

1.  前言

1.1.  集成方式

Spring Boot中集成Elasticsearch有4种方式:

  1. REST Client

  2. Jest

  3. Spring Data

  4. Spring Data Elasticsearch Repositories

本文用后面两种方式来分别连接并操作Elasticsearch

1.2.  环境与配置

  • 服务端:elasticsearch-6.3.2    1台

  • 客户端:elasticsearch 6.4.1

  • 服务端配置文件:elasticsearch.yml

cluster.name: my-application
network.host: 192.168.1.134
http.port: 9200

/etc/security/limits.conf

cheng soft nofile 65536
cheng hard nofile 65536

/etc/sysctl.conf

vm.max_map_count=262144

1.3.  版本

Spring Boot 2.0.5默认的elasticsearch版本很低,这里我们用最新版本6.4.1

如果启动过程中出现

java.lang.NoClassDefFoundError: org/elasticsearch/common/transport/InetSocketTransportAddress

则说明,elasticsearch依赖的jar包版本不一致,统一改成6.4.1即可

另外,Spring Boot 2.0.5依赖的spring-data-elasticsearch版本是3.0.1,需要升级到3.1.0

d627b2fbb26b89535c9fe8d638a7d880.png

2.  依赖

<?xml version="1.0" encoding="UTF-8"?>
"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">4.0.0com.cjs.examplecjs-elasticsearch-example0.0.1-SNAPSHOTjarcjs-elasticsearch-exampleorg.springframework.bootspring-boot-starter-parent2.0.5.RELEASEUTF-8UTF-81.86.4.13.1.0.RELEASEorg.elasticsearchelasticsearch${elasticsearch.version}org.elasticsearch.clienttransport${elasticsearch.version}org.elasticsearch.clientelasticsearch-rest-client${elasticsearch.version}org.elasticsearch.plugintransport-netty4-client${elasticsearch.version}org.springframework.dataspring-data-elasticsearch${spring.data.elasticsearch.version}org.springframework.bootspring-boot-starter-data-elasticsearchorg.springframework.bootspring-boot-starter-weborg.projectlomboklomboktrueorg.springframework.bootspring-boot-starter-testtestorg.springframework.bootspring-boot-maven-plugin

3.  application.properties

spring.data.elasticsearch.cluster-name=my-application
spring.data.elasticsearch.cluster-nodes=192.168.1.134:9300

也许,大家会疑惑,配置文件中明明写的端口是9200,为何这里配置文件中连接的时候写的端口是9300呢?

因为,配置9200是通过HTTP连接的端口,9300是TCP连接的端口

6fd3332f59154294b94dcff1433c15c8.png

4.  操作

4.1.  使用Spring Data Elasticsearch Repositories操作Elasticsearch

首先,定义一个实体类

package com.cjs.example.entity;

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

import java.io.Serializable;

@Data
@Document(indexName = "commodity")
public class Commodity implements Serializable {

@Id
private String skuId;

private String name;

private String category;

private Integer price;

private String brand;

private Integer stock;

}

这里定义了Commodity实例,表示商品。在Elasticsearch 6.X 版本中,不建议使用type,而且在7.X版本中将会彻底废弃type,所以此处我只指定了indexName,没有指定type。这里,一个Commodity代表一个商品,同时代表一条索引记录。

类比关系型数据库的话,Index相当于表,Document相当于记录

然后,需要自己定义一个接口,并继承ElasticsearchRepository

a025a897b5542dd9548207483bac94f1.png

package com.cjs.example.dao;

import com.cjs.example.entity.Commodity;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface CommodityRepository extends ElasticsearchRepository {
}

这里的Repository相当于DAO,操作mysql还是elasticsearch都是一样的

接下来,定义service接口

package com.cjs.example.service;

import com.cjs.example.entity.Commodity;
import org.springframework.data.domain.Page;

import java.util.List;

public interface CommodityService {

long count();

Commodity save(Commodity commodity);

void delete(Commodity commodity);

Iterable getAll();
List getByName(String name);
Page pageQuery(Integer pageNo, Integer pageSize, String kw);
}

实现类

package com.cjs.example.service.impl;

import com.cjs.example.entity.Commodity;
import com.cjs.example.dao.CommodityRepository;
import com.cjs.example.service.CommodityService;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class CommodityServiceImpl implements CommodityService {

@Autowired
private CommodityRepository commodityRepository;


@Overridepublic long count() {
return commodityRepository.count();
}

@Overridepublic Commodity save(Commodity commodity) {
return commodityRepository.save(commodity);
}

@Overridepublic void delete(Commodity commodity) {
commodityRepository.delete(commodity);
// commodityRepository.deleteById(commodity.getSkuId());
}

@Override
public Iterable getAll() {return commodityRepository.findAll();
}
@Overridepublic List getByName(String name) {
Listlist = new ArrayList<>();
MatchQueryBuilder matchQueryBuilder = new MatchQueryBuilder("name", name);
Iterable iterable = commodityRepository.search(matchQueryBuilder);
iterable.forEach(e->list.add(e));return list;
}
@Overridepublic Page pageQuery(Integer pageNo, Integer pageSize, String kw) {
SearchQuery searchQuery = new NativeSearchQueryBuilder()
.withQuery(QueryBuilders.matchPhraseQuery("name", kw))
.withPageable(PageRequest.of(pageNo, pageSize))
.build();return commodityRepository.search(searchQuery);
}
}

在这个Service中演示了增删查改操作,还有分页查询

最后,写一个测试类测试其中的方法

package com.cjs.example;

import com.cjs.example.entity.Commodity;
import com.cjs.example.service.CommodityService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Page;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.List;

@RunWith(SpringRunner.class)
@SpringBootTest
public class CjsElasticsearchExampleApplicationTests {

@Autowired
private CommodityService commodityService;

@Testpublic void contextLoads() {
System.out.println(commodityService.count());
}

@Testpublic void testInsert() {
Commodity commodity = new Commodity();
commodity.setSkuId("1501009001");
commodity.setName("原味切片面包(10片装)");
commodity.setCategory("101");
commodity.setPrice(880);
commodity.setBrand("良品铺子");
commodityService.save(commodity);

commodity = new Commodity();
commodity.setSkuId("1501009002");
commodity.setName("原味切片面包(6片装)");
commodity.setCategory("101");
commodity.setPrice(680);
commodity.setBrand("良品铺子");
commodityService.save(commodity);

commodity = new Commodity();
commodity.setSkuId("1501009004");
commodity.setName("元气吐司850g");
commodity.setCategory("101");
commodity.setPrice(120);
commodity.setBrand("百草味");
commodityService.save(commodity);

}

@Testpublic void testDelete() {
Commodity commodity = new Commodity();
commodity.setSkuId("1501009002");
commodityService.delete(commodity);
}

@Testpublic void testGetAll() {
Iterable iterable = commodityService.getAll();
iterable.forEach(e->System.out.println(e.toString()));
}
@Testpublic void testGetByName() {
Listlist = commodityService.getByName("面包");
System.out.println(list);
}
@Testpublic void testPage() {
Page page = commodityService.pageQuery(0, 10, "切片");
System.out.println(page.getTotalPages());
System.out.println(page.getNumber());
System.out.println(page.getContent());
}
}

以上,便是使用Elasticsearch Repositories的方式

4.2.  使用ElasticsearchTemplate方式操作Elasticsearch

package com.cjs.example;

import com.cjs.example.entity.Commodity;
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.boot.test.context.SpringBootTest;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.*;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.List;

@RunWith(SpringRunner.class)
@SpringBootTest
public class ElasticsearchTemplateTest {

@Autowired
public ElasticsearchTemplate elasticsearchTemplate;

@Testpublic void testInsert() {
Commodity commodity = new Commodity();
commodity.setSkuId("1501009005");
commodity.setName("葡萄吐司面包(10片装)");
commodity.setCategory("101");
commodity.setPrice(160);
commodity.setBrand("良品铺子");

IndexQuery indexQuery = new IndexQueryBuilder().withObject(commodity).build();
elasticsearchTemplate.index(indexQuery);
}

@Testpublic void testQuery() {
SearchQuery searchQuery = new NativeSearchQueryBuilder()
.withQuery(QueryBuilders.matchQuery("name", "吐司"))
.build();
Listlist = elasticsearchTemplate.queryForList(searchQuery, Commodity.class);
System.out.println(list);
}
}

ElasticsearchTemplate是自动配置的

7071956294aec6bc0398212798d204b3.png

5.  演示

2d4d53bd8e15d80f6ff9fc0fe46eb6d1.png

6. 工程结构

c8d7f6565ec2f84a3bb66d9f87b43121.png

7.  参考

1a3ccb00d90fca3545f3928272b58706.png

推荐阅读

(点击标题可跳转阅读)

查询亿级数据毫秒级返回!牛逼哄哄的 ElasticSearch 是如何做到的?

搜索引擎选开源的 ElasticSearch 还是商业的 Splunk

全文搜索引擎 Elasticsearch 入门

看完本文有收获?请转发分享给更多人

关注「ImportNew」,提升Java技能

f8e772cbf6c2656eb81958f6416a24a8.png

好文章,我在看❤️

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值