Spring Data ElasticSearch 常用API调用

1.创建一个maven工程

my-es

pom

    
        
            org.elasticsearch
            elasticsearch
            5.6.8
        
        
            org.elasticsearch.client
            transport
            5.6.8
        
        
            junit
            junit
            4.12
        
        
            org.springframework.data
            spring-data-elasticsearch
            3.0.5.RELEASE
        
        
            org.springframework
            spring-test
            5.0.4.RELEASE
        
    

2.编写applicationConetext.xml配置



    
    
    
    
    
    
    
    
    
    
    
    
    
        
    


如果设置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 {

	List findByTitleAndContent(String title, String content);

	Page findByTitleOrContent(String title, String content, Pageable pageable);

	Page 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 list);

	/**
	 * 查询所有数据
	 *
	 * @return
	 */
	public Iterable 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 list) {
		this.itemRepository.saveAll(list);
	}

	public Iterable findAll() {
		Iterable 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 items = this.itemService.findAll();

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

测试

6.1 测试创建索引

执行方法

验证

Spring Data ElasticSearch 常用API调用_第1张图片

Spring Data ElasticSearch 常用API调用_第2张图片

Spring Data ElasticSearch 常用API调用_第3张图片

6.2 测试添加索引

Spring Data ElasticSearch 常用API调用_第4张图片

6.3 测试查询索引

Spring Data ElasticSearch 常用API调用_第5张图片

6.4 测试修改索引

Spring Data ElasticSearch 常用API调用_第6张图片

Spring Data ElasticSearch 常用API调用_第7张图片

6.5 测试删除索引

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

Spring Data ElasticSearch 常用API调用_第8张图片

Spring Data ElasticSearch 常用API调用_第9张图片

7.批量添加索引

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

	@Autowired
	private ItemRepository itemRepository;

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

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

		//封装数据
		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);
	}

Spring Data ElasticSearch 常用API调用_第10张图片

8.查询全部索引

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

}
public class ItemServiceImpl implements ItemService {

	@Autowired
	private ItemRepository itemRepository;

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

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

 Spring Data ElasticSearch 常用API调用_第11张图片

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

public interface ItemService {

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

	@Autowired
	private ItemRepository itemRepository;

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

该方法需要 

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

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

Spring Data ElasticSearch 常用API调用_第12张图片

10.自定义方法查询

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

关键字 命名规则 解释 实例
and findByField1AndField2 根据Field1和Field2获得数据 findByTitleAndContent
or findByField1OrField2 根据Field1或Field2获得数据 findByTitleOrContent
is findByField 根据Field获得数据 findByTitle
not findByFieldNot 根据Field获得补集数据 findByTitleNot
between findByFieldBetween 获得指定范围的数据 findByPriceBetween
lessThanEqual findByFieldLessThan 获得小于等于指定值的数据 findByPriceLessThan
GreaterThanEqual findByFieldGreaterThan 获取大于等于指定值的数据 findByPriceGreaterThan
Before findByFieldBefore 获得小于等于指定值的数据 findByPriceBefore
After findByFieldAfter 获取大于等于指定值的数据 findByPriceAfter
Like findByFieldLike 条件查询 findByNameLike
StartingWith findByFieldStartingWith 首字符查询 findByNameStartingWith
EndingWith findByFieldEndingWith 末尾字符查询 findByNameEndingWith
Contains/Containing findByFieldContaining 模糊查询 findByNameContaining
In findByFieldIn(Collectionnames) 多条件 查询 findByNameIn(Collectionnames)
NotIn findByFieldNotIn(Collectionnames) 多条件不成立查询 findByNameNotIn(Collectionnames)
Near findByFieldNear 是否存在 findByStoreNear
True findByFieldTrue 获取Field为true的数据 findByAvailableTrue
False findByFieldFalse 获取Field为false的数据 findByAvailableFalse
OrderBy findByFieldTrueOrderByFieldDesc 获取倒序的数据 findByAvailableTrueOrderByNameDesc
public interface ItemRepository extends ElasticsearchRepository {

	List findByTitleAndContent(String title, String content);

	Page findByTitleOrContent(String title, String content, Pageable pageable);

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

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

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

	/**
	 * 根据标题或内容分页查询,并集
	 *
	 * @param title
	 * @param content
	 * @param page
	 * @param rows
	 * @return
	 */
	Page 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 findByTitleAndContentAndIdBetween(String title, String content, int min, int max, int page, int rows);
}
public class ItemServiceImpl implements ItemService {

	@Autowired
	private ItemRepository itemRepository;

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

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

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

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

		return items;
	}

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

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

	//复杂查询
	//根据title和Content进行查询,交集
	@Test
	public void testFindByTitleAndContent() {
		List 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 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 page = this.itemService.findByTitleAndContentAndIdBetween("ES", "job", 5, 9, 1, 10);

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

测试

10.1 测试分页查询

Spring Data ElasticSearch 常用API调用_第13张图片

10.2 测试复杂查询,交集

10.3 测试分页查询,并集

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

Spring Data ElasticSearch 常用API调用_第14张图片

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

public interface ItemService {

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

 

@Service
public class ItemServiceImpl implements ItemService {

	@Autowired
	private ItemRepository itemRepository;

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

Spring Data ElasticSearch 常用API调用_第15张图片

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

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

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

结束!

你可能感兴趣的:(ElasticSearch,Spring)