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: 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() {}@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*/
@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 {@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();
}
@Service
public 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);
}
@Service
public 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(Collection<String>names) 多条件 查询 findByNameIn(Collection<String>names)
NotIn findByFieldNotIn(Collection<String>names) 多条件不成立查询 findByNameNotIn(Collection<String>names)
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;}
}
    //分页查询数据@Testpublic void testFindByPage() {Page<Item> page = this.itemService.findByPage(1, 5);for (Item item : page.getContent()) {System.out.println(item);}}//复杂查询//根据title和Content进行查询,交集@Testpublic 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进行分页查询,并集@Testpublic void testFindByTitleOrContent() {Page<Item> page = this.itemService.findByTitleOrContent("8", "9", 1, 5);for (Item item : page.getContent()) {System.out.println(item);}}//根据Title或者Content和Id的范围,进行分页查询@Testpublic 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 {@Autowiredprivate ItemRepository itemRepository;@Overridepublic Iterable<Item> findBaseQuery(String title, String properties) {// 词条查询MatchQueryBuilder queryBuilder = QueryBuilders.matchQuery(title, properties);Iterable<Item> items = this.itemRepository.search(queryBuilder);return items;}
}
 // 根据title查询@Testpublic 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

结束!

Spring Data ElasticSearch 常用API调用相关推荐

  1. Lucene 和 Kibana、ElasticSeach、Spring Data ElasticSearch

    什么是全文检索 数据分类 生活中的数据总体分为两种:结构化数据和非结构化数据. 结构化数据 - 行数据,可以用二维表结构来逻辑表达实现的数据:指具有固定格式或有限长度的数据,如数据库,元数据等. 非结 ...

  2. Spring Data ElasticSearch 3.2版本发布,相关新特性说明

    由于ElasticSearch更新的速度非常的快,那么就造成了一些常见的Java交互API更新速度无法匹配最新的版本等情况,比如Spring Data ElasticSearch.对于习惯了使用其他类 ...

  3. SpringBoot整合Spring Data Elasticsearch

    特点: 分布式,无需人工搭建集群(solr就需要人为配置,使用Zookeeper作为注册中心) Restful风格,一切API都遵循Rest原则,容易上手 近实时搜索,数据更新在Elasticsear ...

  4. 【javaWeb微服务架构项目——乐优商城day07】——Elasticsearch介绍和安装及使用(安装kibana,安装ik分词器,Spring Data Elasticsearch,高级查询)

    文章目录 0.学习目标 1.Elasticsearch介绍和安装 1.1.简介 1.1.1.Elastic 1.1.2.Elasticsearch 1.1.3.版本 1.2.安装和配置 1.2.1.新 ...

  5. 通过Spring Data Elasticsearch操作ES

    Elasticsearch Elasticsearch (ES)是一个基于Lucene构建的开源.分布式.RESTful 接口全文搜索引擎.Elasticsearch 还是一个分布式文档数据库,其中每 ...

  6. Spring Data ElasticSearch入门案例

    Spring Data ElasticSearch入门案例 创建maven工程elasticsearch_springdata 基于maven导入坐标 导入spring data elasticsea ...

  7. Elasticsearch 实战1:ES 项目实战(一)Java 集成 Spring Data Elasticsearch(一):简介及环境搭建

    一:前语 1.项目文档 CSDN 专栏:<Elasticsearch 入门和项目实战> 博客路径: https://blog.csdn.net/a767815662/category_91 ...

  8. 【Spring Data ElasticSearch】高级查询,聚合

    [Spring Data ElasticSearch]高级查询,聚合 1. 高级查询 1.1 基本查询 1.2 自定义查询 1.3 分页查询 1.4 排序 2. 聚合 2.1 聚合为桶 2.2 嵌套聚 ...

  9. Spring系列学习之Spring Data Elasticsearch数据访问

    英文原文:https://spring.io/projects/spring-data-elasticsearch 目录 概述 特性 快速开始 学习 文档 概述 Elasticsearch的Sprin ...

最新文章

  1. 这是一张很有趣的图片, 通常女性会先看到月亮, 男性会先看到人脸. 如果相反, 表示你体内的异性荷尔蒙偏高哦!...
  2. [转]代码分析工具FxCop1.36之一:介绍与使用
  3. [备忘]macOS和Windows下很赞的软件
  4. 马化腾和扎克伯格,为什么抢着押注元宇宙?
  5. redis设置为前台运行的方式
  6. AOL、WebEx共同开发新AIM即时通讯
  7. php程序访问mysql数据实现查询_PHP+MySql实现后台数据的读取
  8. Mac上的一位数密码你知道吗
  9. php 判断函数禁用,php禁用函数设置及查看方法的介绍(附示例)
  10. IDC:无线数字化转型持续进行 第二季度全球企业WLAN市场强劲增长
  11. 正则表达式常用的js验证
  12. 微信小程序记录v1.0
  13. 深度可分离卷积vs标准卷积
  14. box-sizing的属性值
  15. 一题多解×2(流的概念+递归)
  16. 亚马逊运营技巧亚马逊 ASIN 和 SKU有什么作用?区别在哪里
  17. c51单片机光电门测反应时间(实战小项目)
  18. c语言polygon函数,C. Polygon for the Angle(几何)
  19. c语言关键词中英翻译机编程,C语言关键字中英翻译机.doc
  20. 计算机清理垃圾文件丢失怎么恢复,如何恢复windows电脑垃圾箱中清除的文件

热门文章

  1. 项目经理常说的鱼骨图是什么?鱼骨图可以用来解决哪些项目难题?
  2. 【无标题】word2007删除页眉横线(亲测方法二)
  3. 【新手基础教程】SP-MOD之 Eink电子水墨屏的使用
  4. HTTP cookies劫持实验
  5. 基本的图像处理和操作——图像去噪
  6. 2. t-NSE 可视化
  7. Js——案例实现图片数字时钟
  8. seaborn.jointpolt绘图坐标轴问题seaborn, xlabel,ylabel
  9. 图片去水印步骤-图片去水印的方法
  10. Python - SciPy - ECG信号的谱分析及数字滤波