Spring Data ElasticSearch 常用API调用

1.创建一个maven工程

my-es

pom

    <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>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-elasticsearch</artifactId>
            <version>3.0.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.0.4.RELEASE</version>
        </dependency>
    </dependencies>

2.编写applicationConetext.xml配置

<?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">
    
    <!-- 扫描Dao包,自动创建实例 -->
    <elasticsearch:repositories base-package="com.hikktn.dao"/>
    
    <!-- 扫描Service包,创建Service的实体 -->
    <context:component-scan base-package="com.hikktn.service"/>
    
    <!-- 配置elasticSearch的连接 -->
    <elasticsearch:transport-client id="client" cluster-nodes="localhost:9300" cluster-name="my-application"/>
    
    
    <!-- spring data elasticSearcheDao 必须继承 ElasticsearchTemplate -->
    <bean id="elasticsearchTemplate"
          class="org.springframework.data.elasticsearch.core.ElasticsearchTemplate">
        <constructor-arg name="client" ref="client"/>
    </bean>

</beans>

如果设置cluster-name配置,那么需要开启elasticsearch.yml的配置

# ======================== Elasticsearch Configuration =========================
#
# NOTE: Elasticsearch comes with reasonable defaults for most settings.
#       Before you set out to tweak and tune the configuration, make sure you
#       understand what are you trying to accomplish and the consequences.
#
# The primary way of configuring a node is via this file. This template lists
# the most important settings you may want to configure for a production cluster.
#
# Please consult the documentation for further information on configuration options:
# https://www.elastic.co/guide/en/elasticsearch/reference/index.html
#
# ---------------------------------- Cluster -----------------------------------
#
# Use a descriptive name for your cluster:
#
cluster.name: my-application
#
# ------------------------------------ Node ------------------------------------
#
# Use a descriptive name for the node:
#
node.name: node-1
#
# Add custom attributes to the node:
#
#node.attr.rack: r1
#
# ----------------------------------- Paths ------------------------------------
#
# Path to directory where to store the data (separate multiple locations by comma):
#
#path.data: /path/to/data
#
# Path to log files:
#
#path.logs: /path/to/logs
#
# ----------------------------------- Memory -----------------------------------
#
# Lock the memory on startup:
#
#bootstrap.memory_lock: true
#
# Make sure that the heap size is set to about half the memory available
# on the system and that the owner of the process is allowed to use this
# limit.
#
# Elasticsearch performs poorly when the system is swapping the memory.
#
# ---------------------------------- Network -----------------------------------
#
# Set the bind address to a specific IP (IPv4 or IPv6):
#
#network.host: 192.168.0.1
#
# Set a custom port for HTTP:
#
#http.port: 9200
#
# For more information, consult the network module documentation.
#
# --------------------------------- Discovery ----------------------------------
#
# Pass an initial list of hosts to perform discovery when new node is started:
# The default list of hosts is ["127.0.0.1", "[::1]"]
#
#discovery.zen.ping.unicast.hosts: ["host1", "host2"]
discovery.zen.ping.unicast.hosts: ["127.0.0.1"]
client.transport.ping_timeout: 60s
#
# Prevent the "split brain" by configuring the majority of nodes (total number of master-eligible nodes / 2 + 1):
#
#discovery.zen.minimum_master_nodes: 3
#
# For more information, consult the zen discovery module documentation.
#
# ---------------------------------- Gateway -----------------------------------
#
# Block initial recovery after a full cluster restart until N nodes are started:
#
#gateway.recover_after_nodes: 3
#
# For more information, consult the gateway module documentation.
#
# ---------------------------------- Various -----------------------------------
#
# Require explicit names when deleting indices:
#
#action.destructive_requires_name: true
http.cors.enabled: true
http.cors.allow-origin: "*"
network.host: 127.0.0.1

3.编写pojo实体类

注解解释:

@Document :文档对象

  • indexName:索引名称
  • type:索引类型
  • shards:分片数量,默认5
  • replicas:副本数量,默认1

@Feild:成员变量

  • type:字段类型
  • index:是否索引,默认为true
  • store:是否存储,默认false
  • analyzer:分词器
  • searchAnalyzer:备用分词器
package com.hikktn.pojo;

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;

/**
 * @ClassName Item
 * @Description TODO
 * @Author lisonglin
 * @Date 2021/5/7 16:37
 * @Version 1.0
 */
@Document(indexName = "item", type = "item")
public class Item {
	@Id
	@Field(index = true, store = true, type = FieldType.Integer)
	private Integer id;
	@Field(index = true, store = true, analyzer = "ik_smart", searchAnalyzer = "ik_smart", type = FieldType.text)
	private String title;
	@Field(index = true, store = true, analyzer = "ik_smart", 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;
	}

	public Item(Integer id, String title, String content) {
		this.id = id;
		this.title = title;
		this.content = content;
	}

	public Item() {
	}

	@Override
	public String toString() {
		return "Item{" + "id=" + id + ", title='" + title + '\'' + ", content='" + content + '\'' + '}';
	}
}

3.编写dao

package com.hikktn.dao;

import com.hikktn.pojo.Item;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;

import java.util.List;

/**
 * @ClassName ItemRepository
 * @Description TODO
 * @Author lisonglin
 * @Date 2021/5/7 16:40
 * @Version 1.0
 */
public interface ItemRepository extends ElasticsearchRepository<Item, Integer> {

	List<Item> findByTitleAndContent(String title, String content);

	Page<Item> findByTitleOrContent(String title, String content, Pageable pageable);

	Page<Item> findByTitleAndContentAndIdBetween(String title, String content, int min, int max, Pageable pageable);
}

4.编写service

package com.hikktn.service;

import com.hikktn.pojo.Item;

import java.util.List;

/**
 * @ClassName ItemService
 * @Description TODO
 * @Author lisonglin
 * @Date 2021/5/7 16:41
 * @Version 1.0
 */
public interface ItemService {

}

5.编写service.impl

package com.hikktn.service.impl;

import com.hikktn.dao.ItemRepository;
import com.hikktn.pojo.Item;
import com.hikktn.service.ItemService;

/**
 * @ClassName ItemServiceImpl
 * @Description TODO
 * @Author lisonglin
 * @Date 2021/5/7 16:41
 * @Version 1.0
 */
@Service
public class ItemServiceImpl implements ItemService {

}

6.ElasticSearch 基本使用CRUD

public interface ItemService {
	/**
	 * 新增
	 *
	 * @param item
	 */
	void save(Item item);

	/**
	 * 删除
	 *
	 * @param item
	 */
	void delete(Item item);

	/**
	 * 批量保存
	 *
	 * @param list
	 */
	void saveAll(List<Item> list);

	/**
	 * 查询所有数据
	 *
	 * @return
	 */
	public Iterable<Item> findAll();
}

 

@Service
public class ItemServiceImpl implements ItemService {

	@Autowired
	private ItemRepository itemRepository;

	public void save(Item item) {
		this.itemRepository.save(item);
	}

	public void delete(Item item) {
		this.itemRepository.delete(item);
	}

	public void saveAll(List<Item> list) {
		this.itemRepository.saveAll(list);
	}

	public Iterable<Item> findAll() {
		Iterable<Item> items = this.itemRepository.findAll();
		return items;
	}
}

elasticsearchTemplate 是已经封装好的各种方法,不需要程序员很麻烦的写方法调用。

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

	@Autowired
	private ItemService itemService;
	@Autowired
	private ElasticsearchTemplate elasticsearchTemplate;

    /**
	 * 添加索引,并添加映射
	 */
	@Test
	public void createIndex() {
		this.elasticsearchTemplate.createIndex(Item.class);
		this.elasticsearchTemplate.putMapping(Item.class);
	}

	/**
	 * 添加文档
	 *
	 */
	@Test
	public void testSave() {
		Item item = new Item();
		item.setId(100);
		item.setTitle("SpringData ES");
		item.setContent("今天我们使用SpringData ES完成搜索功能。");

		this.itemService.save(item);

	}

	/**
     * 修改,和新增的代码是一样的,如果id存在就是修改,如果id不存在就是新增
	 *
	 */
	@Test
	public void testUpdate() {
		Item item = new Item();
		item.setId(100);
		item.setTitle("SpringData ES");
		item.setContent("今天我们使用SpringData ES完成job搜索功能。");

		this.itemService.save(item);

	}

	/**
	 * 删除索引
	 */
	@Test
	public void testDelete() {
		Item item = new Item();
		item.setId(100);

		this.itemService.delete(item);
	}

    /**
	 * 查询索引
	 */
	@Test
	public void testFindAll() {
		Iterable<Item> items = this.itemService.findAll();

		for (Item item : items) {
			System.out.println(item);
		}
	}
}

测试

6.1 测试创建索引

执行方法

验证

6.2 测试添加索引

6.3 测试查询索引

6.4 测试修改索引

6.5 测试删除索引

只是将里面的文档删除,索引依然存在

7.批量添加索引

public interface ItemService {
	/**
	 * 查询所有数据
	 *
	 * @return
	 */
	public Iterable<Item> findAll();
}
@Service
public class ItemServiceImpl implements ItemService {

	@Autowired
	private ItemRepository itemRepository;

	public Iterable<Item> findAll() {
		Iterable<Item> items = this.itemRepository.findAll();
		return items;
	}
}
	@Autowired
	private ItemService itemService;

	// 批量保存
	@Test
	public void testSaveAll() {
		//创建集合
		List<Item> list = new ArrayList<Item>();

		//封装数据
		for (int i = 1; i < 10; i++) {
			Item item = new Item();
			item.setId(i);
			item.setTitle("SpringData ES " + i);
			item.setContent("今天我们使用SpringData ES完成job搜索功能。" + i);

			list.add(item);
		}

		//批量保存
		this.itemService.saveAll(list);
	}

8.查询全部索引

public interface ItemService {
    
	/**
	 * 查询所有数据
	 *
	 * @return
	 */
	public Iterable<Item> findAll();

}
public class ItemServiceImpl implements ItemService {

	@Autowired
	private ItemRepository itemRepository;

	public Iterable<Item> findAll( String properties) {
		return this.itemRepository.findAll(Sort.by(Sort.Direction.DESC,properties));
	}
}
	//查询所有数据
	@Test
	public void testFindAll() {
		Iterable<Item> items = this.itemService.findAll();

		for (Item item : items) {
			System.out.println(item);
		}
	}

 

9.查询全部索引,按照id倒序

public interface ItemService {

	/**
	 * 排序查询
	 * @param properties
	 * @return
	 */
	public Iterable<Item> findAll(String properties);
}
@Service
public class ItemServiceImpl implements ItemService {

	@Autowired
	private ItemRepository itemRepository;

	public Iterable<Item> findAll( String properties) {
		return this.itemRepository.findAll(Sort.by(Sort.Direction.DESC,properties));
	}
}

该方法需要 

	// 根据id倒序
	@Test
	public void testFindAllDesc() {
		Iterable<Item> items = this.itemService.findAll("title");

		for (Item item : items) {
			System.out.println(item);
		}
	}

10.自定义方法查询

不可以编写一个没有属性的方法,否则会报找不到的异常

关键字命名规则解释实例
andfindByField1AndField2根据Field1和Field2获得数据findByTitleAndContent
orfindByField1OrField2根据Field1或Field2获得数据findByTitleOrContent
isfindByField根据Field获得数据findByTitle
notfindByFieldNot根据Field获得补集数据findByTitleNot
betweenfindByFieldBetween获得指定范围的数据findByPriceBetween
lessThanEqualfindByFieldLessThan获得小于等于指定值的数据findByPriceLessThan
GreaterThanEqualfindByFieldGreaterThan获取大于等于指定值的数据findByPriceGreaterThan
BeforefindByFieldBefore获得小于等于指定值的数据findByPriceBefore
AfterfindByFieldAfter获取大于等于指定值的数据findByPriceAfter
LikefindByFieldLike条件查询findByNameLike
StartingWithfindByFieldStartingWith首字符查询findByNameStartingWith
EndingWithfindByFieldEndingWith末尾字符查询findByNameEndingWith
Contains/ContainingfindByFieldContaining模糊查询findByNameContaining
InfindByFieldIn(Collection<String>names)多条件 查询findByNameIn(Collection<String>names)
NotInfindByFieldNotIn(Collection<String>names)多条件不成立查询findByNameNotIn(Collection<String>names)
NearfindByFieldNear是否存在findByStoreNear
TruefindByFieldTrue获取Field为true的数据findByAvailableTrue
FalsefindByFieldFalse获取Field为false的数据findByAvailableFalse
OrderByfindByFieldTrueOrderByFieldDesc获取倒序的数据findByAvailableTrueOrderByNameDesc
public interface ItemRepository extends ElasticsearchRepository<Item, Integer> {

	List<Item> findByTitleAndContent(String title, String content);

	Page<Item> findByTitleOrContent(String title, String content, Pageable pageable);

	Page<Item> findByTitleAndContentAndIdBetween(String title, String content, int min, int max, Pageable pageable);
}
public interface ItemService {

/**
	 * 分页查询
	 *
	 * @param page
	 * @param rows
	 * @return
	 */
	Page<Item> findByPage(int page, int rows);

	/**
	 * 根据标题和内容查询,交集
	 *
	 * @param title
	 * @param content
	 * @return
	 */
	List<Item> findByTitleAndContent(String title, String content);

	/**
	 * 根据标题或内容分页查询,并集
	 *
	 * @param title
	 * @param content
	 * @param page
	 * @param rows
	 * @return
	 */
	Page<Item> findByTitleOrContent(String title, String content, Integer page, Integer rows);

	/**
	 * 根据Title或者Content和Id的范围,进行分页查询
	 *
	 * @param title
	 * @param content
	 * @param min
	 * @param max
	 * @param page
	 * @param rows
	 * @return
	 */
	Page<Item> findByTitleAndContentAndIdBetween(String title, String content, int min, int max, int page, int rows);
}
public class ItemServiceImpl implements ItemService {

	@Autowired
	private ItemRepository itemRepository;

	public Page<Item> findByPage(int page, int rows) {
		Page<Item> items = this.itemRepository.findAll(PageRequest.of(page, rows));
		return items;
	}

	public List<Item> findByTitleAndContent(String title, String content) {
		List<Item> list = this.itemRepository.findByTitleAndContent(title, content);
		return list;
	}

	public Page<Item> findByTitleOrContent(String title, String content, Integer page, Integer rows) {

		Page<Item> items = this.itemRepository.findByTitleOrContent(title, content, PageRequest.of(page - 1, rows));

		return items;
	}

	public Page<Item> findByTitleAndContentAndIdBetween(String title, String content, int min, int max, int page, int
			rows) {
		Page<Item> items = this.itemRepository.findByTitleAndContentAndIdBetween(title, content, min, max, PageRequest
				.of(page - 1, rows));
		return items;
	}
}
    //分页查询数据
	@Test
	public void testFindByPage() {
		Page<Item> page = this.itemService.findByPage(1, 5);

		for (Item item : page.getContent()) {
			System.out.println(item);
		}
	}

	//复杂查询
	//根据title和Content进行查询,交集
	@Test
	public void testFindByTitleAndContent() {
		List<Item> list = this.itemService.findByTitleAndContent("SpringData ES 9", "今天我们使用SpringData ES完成job搜索功能。9");
		for (Item item : list) {
			System.out.println(item);
		}
	}


	//根据title或者Content进行分页查询,并集
	@Test
	public void testFindByTitleOrContent() {
		Page<Item> page = this.itemService.findByTitleOrContent("8", "9", 1, 5);

		for (Item item : page.getContent()) {
			System.out.println(item);
		}
	}


	//根据Title或者Content和Id的范围,进行分页查询
	@Test
	public void testFindByTitleAndContentAndIdBetween() {
		Page<Item> page = this.itemService.findByTitleAndContentAndIdBetween("ES", "job", 5, 9, 1, 10);

		for (Item item : page.getContent()) {
			System.out.println(item);
		}
	}

测试

10.1 测试分页查询

10.2 测试复杂查询,交集

10.3 测试分页查询,并集

10.4 测试分页查询和范围查询

11.单词条查询--自行编程

public interface ItemService {

	/**
	 * 单词条查询
	 * @param title
	 * @param properties
	 * @return
	 */
	Iterable<Item> findBaseQuery(String title,String properties);
}

 

@Service
public class ItemServiceImpl implements ItemService {

	@Autowired
	private ItemRepository itemRepository;

    	@Override
	public Iterable<Item> findBaseQuery(String title, String properties) {
		// 词条查询
		MatchQueryBuilder queryBuilder = QueryBuilders.matchQuery(title, properties);
		Iterable<Item> items = this.itemRepository.search(queryBuilder);
		return items;
	}
}
	// 根据title查询
	@Test
	public void testBaseQuery(){
		Iterable<Item> items = this.itemService.findBaseQuery("title", "ES");
		items.forEach(System.out::println);
	}

后续的各种自定义编程,可以参照elasticsearch-rest-high-level-client

基本上只需要NativeSearchQueryBuilder构建一下,其他代码完全按照实例抄一下就行。

https://blog.csdn.net/qq_41520636/article/details/116132943

结束!

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hikktn

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值