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/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/data/elasticsearchhttp://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: truehttp.cors.enabled: truehttp.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() {}@Overridepublic 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*/@Servicepublic 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();}
@Servicepublic class ItemServiceImpl implements ItemService {@Autowiredprivate 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 {@Autowiredprivate ItemService itemService;@Autowiredprivate ElasticsearchTemplate elasticsearchTemplate;/*** 添加索引,并添加映射*/@Testpublic void createIndex() {this.elasticsearchTemplate.createIndex(Item.class);this.elasticsearchTemplate.putMapping(Item.class);}/*** 添加文档**/@Testpublic void testSave() {Item item = new Item();item.setId(100);item.setTitle("SpringData ES");item.setContent("今天我们使用SpringData ES完成搜索功能。");this.itemService.save(item);}/*** 修改,和新增的代码是一样的,如果id存在就是修改,如果id不存在就是新增**/@Testpublic void testUpdate() {Item item = new Item();item.setId(100);item.setTitle("SpringData ES");item.setContent("今天我们使用SpringData ES完成job搜索功能。");this.itemService.save(item);}/*** 删除索引*/@Testpublic void testDelete() {Item item = new Item();item.setId(100);this.itemService.delete(item);}/*** 查询索引*/@Testpublic 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();}
@Servicepublic class ItemServiceImpl implements ItemService {@Autowiredprivate ItemRepository itemRepository;public Iterable<Item> findAll() {Iterable<Item> items = this.itemRepository.findAll();return items;}}
@Autowiredprivate ItemService itemService;// 批量保存@Testpublic 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 {@Autowiredprivate ItemRepository itemRepository;public Iterable<Item> findAll( String properties) {return this.itemRepository.findAll(Sort.by(Sort.Direction.DESC,properties));}}
//查询所有数据@Testpublic 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);}
@Servicepublic class ItemServiceImpl implements ItemService {@Autowiredprivate ItemRepository itemRepository;public Iterable<Item> findAll( String properties) {return this.itemRepository.findAll(Sort.by(Sort.Direction.DESC,properties));}}
该方法需要
// 根据id倒序@Testpublic void testFindAllDesc() {Iterable<Item> items = this.itemService.findAll("title");for (Item item : items) {System.out.println(item);}}

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<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 {@Autowiredprivate 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, introws) {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
结束!
