【ElasticSearch】spring-data方式操作elasticsearch(一)

这篇具有很好参考价值的文章主要介绍了【ElasticSearch】spring-data方式操作elasticsearch(一)。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。


一、使用spring-data方式进行操作elasticsearch


1.添加依赖

<!-- 添加 elasticsearch 客户端 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>


2.添加ES配置

#使用模板方式
spring:
  elasticsearch:
    rest:
      uris:
      - http://localhost:9200
    

3.添加实体类

package com.tianya.springboot.es.entity;

import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Document(indexName = "people_index", type = "people")
public class PeopleBean {
	
	/**
	 * 主键
	 */
	@Id
	private Long uid ;
	
	/**
	 * 姓名
	 */
	@Field
	private String name ;
	
	/**
	 * 年龄
	 */
	@Field
	private int age ;
	
	/**
	 * 地址
	 */
	@Field
	private String addr ;
	
	/**
	 * 生日
	 */
	@Field
	private String birthDay ;
	
	/**
	 * 职业
	 */
	@Field
	private String professional ;
	
	/**
	 * 兴趣
	 */
	@Field
	private String interest ;
	
}

4.添加repository

package com.tianya.springboot.es.dao;

import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.stereotype.Repository;

import com.tianya.springboot.es.entity.PeopleBean;

@Repository
public interface PeopleEsDao extends ElasticsearchRepository<PeopleBean, Long>{

}

准备操作都做完了,开始进行对elasticsearch操作了,新增一些测试模拟数据


1.1 新增

@SpringBootTest
public class PeopleTest {
	
	@Autowired
	private PeopleEsDao peopleEsDao ;
	
	@Test
	public void insert() {
		
		List<PeopleBean> peopleBeanList = new ArrayList<>();
		peopleBeanList.add(PeopleBean.builder().uid(1L).name("吴彦祖").age(45).birthDay("1977-01-01").addr("香港").professional("演员").interest("赛车").build());
		peopleBeanList.add(PeopleBean.builder().uid(2L).name("吴奇隆").age(55).birthDay("1967-01-01").addr("大陆").professional("演员").interest("唱歌").build());
		peopleBeanList.add(PeopleBean.builder().uid(3L).name("吴京").age(45).birthDay("1977-01-01").addr("大陆").professional("演员").interest("武术").build());
		peopleBeanList.add(PeopleBean.builder().uid(4L).name("古天乐").age(55).birthDay("1967-01-01").addr("香港").professional("演员").interest("唱歌").build());
		peopleBeanList.add(PeopleBean.builder().uid(5L).name("苏炳添").age(35).birthDay("1987-01-01").addr("大陆").professional("运动员").interest("跑步").build());
		peopleBeanList.add(PeopleBean.builder().uid(6L).name("刘亦菲").age(30).birthDay("1992-01-01").addr("大陆").professional("歌手").interest("演戏").build());
		peopleBeanList.add(PeopleBean.builder().uid(7L).name("张杰").age(30).birthDay("1992-01-01").addr("大陆").professional("歌手").interest("健身").build());
		peopleBeanList.add(PeopleBean.builder().uid(8L).name("张家辉").age(45).birthDay("1977-01-01").addr("香港").professional("演员").interest("唱歌").build());
		
        // 新增
		Iterable<PeopleBean> saveResult = peopleEsDao.saveAll(peopleBeanList);
		System.out.println(JSON.toJSONString(saveResult, true));
	}
}

结果:

[
	{
		"addr":"大陆",
		"age":35,
		"birthDay":"1987-01-01",
		"interest":"跑步",
		"name":"苏炳添",
		"professional":"运动员",
		"uid":5
	},
	{
		"addr":"香港",
		"age":45,
		"birthDay":"1977-01-01",
		"interest":"唱歌",
		"name":"张家辉",
		"professional":"演员",
		"uid":8
	},
	{
		"addr":"大陆",
		"age":55,
		"birthDay":"1967-01-01",
		"interest":"唱歌",
		"name":"吴奇隆",
		"professional":"演员",
		"uid":2
	},
	{
		"addr":"香港",
		"age":55,
		"birthDay":"1967-01-01",
		"interest":"唱歌",
		"name":"古天乐",
		"professional":"演员",
		"uid":4
	},
	{
		"addr":"大陆",
		"age":30,
		"birthDay":"1992-01-01",
		"interest":"演戏",
		"name":"刘亦菲",
		"professional":"歌手",
		"uid":6
	},
	{
		"addr":"香港",
		"age":45,
		"birthDay":"1977-01-01",
		"interest":"赛车",
		"name":"吴彦祖",
		"professional":"演员",
		"uid":1
	},
	{
		"addr":"大陆",
		"age":30,
		"birthDay":"1992-01-01",
		"interest":"健身",
		"name":"张杰",
		"professional":"歌手",
		"uid":7
	},
	{
		"addr":"大陆",
		"age":45,
		"birthDay":"1977-01-01",
		"interest":"武术",
		"name":"吴京",
		"professional":"演员",
		"uid":3
	}
]

1.2 查询-所有

@Test
public void get() {
    // 查询所有
    Iterable<PeopleBean> peopleList = peopleEsDao.findAll();
    System.out.println(JSON.toJSONString(peopleList, true));
}

类似SQL:

SELECT * FROM people

1.3 查询-排序

@Test
public void order4Get() {

    // 按照uid进行排序
    Sort orderSort = Sort.by(Order.asc("uid"));
    Iterable<PeopleBean> sortPeopleList = peopleEsDao.findAll(orderSort);
    System.out.println(JSON.toJSONString(sortPeopleList, true));
}

可以按照多个字段进行排序

public static Sort by(Order… orders) ;

类似SQL:

SELECT * FROM people order by uid

1.4 分页查询

@Test
public void page4Get() {

    PageRequest page = PageRequest.of(0, 5, Sort.by(Order.asc("uid")));
    // 分页查询
    Page<PeopleBean> pagePeopleList = peopleEsDao.findAll(page);
    System.out.println(JSON.toJSONString(pagePeopleList, true));
}

类似SQL:

SELECT * FROM people order by uid limit 0,5

结果:

{
	"content":[
		{
			"addr":"香港",
			"age":45,
			"birthDay":"1977-01-01",
			"interest":"赛车",
			"name":"吴彦祖",
			"professional":"演员",
			"uid":1
		},
		{
			"addr":"大陆",
			"age":55,
			"birthDay":"1967-01-01",
			"interest":"唱歌",
			"name":"吴奇隆",
			"professional":"演员",
			"uid":2
		},
		{
			"addr":"大陆",
			"age":45,
			"birthDay":"1977-01-01",
			"interest":"武术",
			"name":"吴京",
			"professional":"演员",
			"uid":3
		},
		{
			"addr":"香港",
			"age":55,
			"birthDay":"1967-01-01",
			"interest":"唱歌",
			"name":"古天乐",
			"professional":"演员",
			"uid":4
		},
		{
			"addr":"大陆",
			"age":35,
			"birthDay":"1987-01-01",
			"interest":"跑步",
			"name":"苏炳添",
			"professional":"运动员",
			"uid":5
		}
	],
	"empty":false,
	"facets":[],
	"first":true,
	"last":false,
	"maxScore":null,
	"number":0,
	"numberOfElements":5,
	"pageable":{
		"offset":0,
		"pageNumber":0,
		"pageSize":5,
		"paged":true,
		"sort":{
			"empty":false,
			"sorted":true,
			"unsorted":false
		},
		"unpaged":false
	},
	"size":5,
	"sort":{"$ref":"$.pageable.sort"},
	"totalElements":8,
	"totalPages":2
}

1.5 搜索-等值查询-Term

@Test
public void search() {

    TermQueryBuilder ageQuery = QueryBuilders.termQuery("age", 45);
	// age = 45
    Iterable<PeopleBean> search = peopleEsDao.search(ageQuery);
    System.out.println("结果:");
    System.out.println(JSON.toJSONString(search, true));
}

类似SQL:

SELECT * FROM people WHERE age = 45

结果:

[
	{
		"addr":"香港",
		"age":45,
		"birthDay":"1977-01-01",
		"interest":"唱歌",
		"name":"张家辉",
		"professional":"演员",
		"uid":8
	},
	{
		"addr":"香港",
		"age":45,
		"birthDay":"1977-01-01",
		"interest":"赛车",
		"name":"吴彦祖",
		"professional":"演员",
		"uid":1
	},
	{
		"addr":"大陆",
		"age":45,
		"birthDay":"1977-01-01",
		"interest":"武术",
		"name":"吴京",
		"professional":"演员",
		"uid":3
	}
]

若是查询中文,需要添加 keyword ,term 是指分词后的 = 查询

@Test
public void searchChinese() {

    // 添加 keyword 的目的是 以后面查询的值整体查询,不要分词,不然查询不到
    TermQueryBuilder termQuery = QueryBuilders.termQuery("addr.keyword", "大陆");

    System.out.println("参数:");
    System.out.println(termQuery.toString(true));

    Iterable<PeopleBean> search = peopleEsDao.search(termQuery);
    System.out.println("结果:");
    System.out.println(JSON.toJSONString(search, true));
}

1.6 搜索-多条件

@Test
public void searchMore() {


    BoolQueryBuilder boolQuery = QueryBuilders.boolQuery()
        .filter(QueryBuilders.termQuery("addr.keyword", "大陆"))
        .filter(QueryBuilders.termQuery("age", 45));

    System.out.println("参数:");
    System.out.println(boolQuery.toString(true));

    Iterable<PeopleBean> search = peopleEsDao.search(boolQuery);
    System.out.println("结果:");
    System.out.println(JSON.toJSONString(search, true));
}

类似SQL:

SELECT * FROM people WHERE addr = '大陆' AND age = 45

结果:

{
    "addr":"大陆",
    "age":45,
    "birthDay":"1977-01-01",
    "interest":"武术",
    "name":"吴京",
    "professional":"演员",
    "uid":3
}

1.7 搜索-范围查询

@Test
public void searchBetweenAnd() {

    // >= 
    // RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("age").gte(55);
    //  between and
    RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("age").from(55).to(66);

    System.out.println("参数:");
    System.out.println(rangeQuery.toString(true));

    Iterable<PeopleBean> search = peopleEsDao.search(rangeQuery);
    System.out.println("结果:");
    System.out.println(JSON.toJSONString(search, true));

}

类似SQL:

SELECT * FROM people WHERE age BETWEEN 55 AND 66

gte >=

gt >

lt <

lte <=

from … to … 类似 between and

1.8 搜索-分页

@Test
public void searchSort() {

    BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery()
        .filter(QueryBuilders.termQuery("professional.keyword", "演员"))
        .filter(QueryBuilders.termQuery("age", 55));
    System.out.println("参数:");
    System.out.println(queryBuilder.toString(true));
    // 分页排序
    PageRequest page = PageRequest.of(0, 5, Sort.by(Order.desc("age"), Order.asc("uid")));
    // 搜索分页查询
    Iterable<PeopleBean> search = peopleEsDao.search(queryBuilder, page);
    System.out.println("结果:");
    System.out.println(JSON.toJSONString(search, true));

}

类似SQL:

SELECT 
* 
FROM people 
WHERE professional = '演员'
AND age = 55
ORDER BY age desc, uid asc
limit 0,5

结果:

[
	{
		"addr":"大陆",
		"age":55,
		"birthDay":"1967-01-01",
		"interest":"唱歌",
		"name":"吴奇隆",
		"professional":"演员",
		"uid":2
	},
	{
		"addr":"香港",
		"age":55,
		"birthDay":"1967-01-01",
		"interest":"唱歌",
		"name":"古天乐",
		"professional":"演员",
		"uid":4
	}
]

1.9 搜索-组合查询-特定输出字段

@Test
public void searchQuery() {

    NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder()
        .withFields("uid","name","age","professional")
        .withFilter(QueryBuilders.termQuery("professional.keyword", "演员"))
        .withQuery(QueryBuilders.rangeQuery("age").gte(45))
        .withSort(SortBuilders.fieldSort("uid"))
        .withPageable(PageRequest.of(0, 3));

    Iterable<PeopleBean> search = peopleEsDao.search(queryBuilder.build());

    System.out.println("结果:");
    System.out.println(JSON.toJSONString(search, true));

}

类似SQL:

select 
	uid,name,age,professional
from people
where professional = '演员'
and age >= 45
order by uid
limit 0,3

结果:文章来源地址https://www.toymoban.com/news/detail-444182.html

[
	{
		"age":45,
		"name":"吴彦祖",
		"professional":"演员",
		"uid":1
	},
	{
		"age":55,
		"name":"吴奇隆",
		"professional":"演员",
		"uid":2
	},
	{
		"age":45,
		"name":"吴京",
		"professional":"演员",
		"uid":3
	}
]

到了这里,关于【ElasticSearch】spring-data方式操作elasticsearch(一)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • Spring Data Elasticsearch 使用(Elasticsearch)

      在项目的 pom.xml 中引⼊Spring Data Elasticsearch的启动器。  需要注意的是,Spring Data Elasticsearch底层使⽤的不是Elasticsearch提供的RestHighLevelClient,⽽是 TransportClient,并不采⽤HTTP协议通信,⽽是访问Elasticsearch对外开放的TCP端⼝。我们在之前集群配置 中,设置的端⼝分别是:9301、

    2024年02月05日
    浏览(41)
  • spring data系列之Spring data ElasticSearch

    Spring data ElasticSearch简介:        Elasticsearch是一个实时的分布式搜索和分析引擎。它底层封装了Lucene框架,可以提供分布式多用户的全文搜索服务。        Spring Data ElasticSearch是SpringData技术对ElasticSearch原生API封装之后的产物,它通过对原生API的封装,使得程序员可以简单的

    2023年04月08日
    浏览(48)
  • Spring Boot中使用Spring Data Elasticsearch访问Elasticsearch

    Elasticsearch是一个分布式的全文搜索和分析引擎,它可以将海量数据进行快速的查询和聚合。Spring Data Elasticsearch是Spring Data家族中的一个成员,它提供了与Elasticsearch的集成,可以方便地使用Spring框架来访问Elasticsearch。 在本文中,我们将会介绍如何在Spring Boot中使用Spring Data

    2024年02月08日
    浏览(48)
  • Elasticsearch版本和Spring Data Elasticsearch版本对应关系

    Elasticsearch版本和Spring Data Elasticsearch版本对应关系 官网说明 【官网说明】:https://docs.spring.io/spring-data/elasticsearch/docs/current/reference/html/#preface.versions Elasticsearch历史版本地址 历史版本:【https://www.elastic.co/cn/downloads/past-releases#elasticsearch】

    2024年02月12日
    浏览(39)
  • Spring Data ElasticSearch简介

    Spring Data是⼀个⽤于简化数据库访问,并⽀持云服务的开源框架。其主要⽬标是使得对数据的访问变 得⽅便快捷,并⽀持map-reduce框架和云计算数据服务。 Spring Data可以极⼤的简化JPA的写法,可 以在⼏乎不⽤写实现的情况下,实现对数据的访问和操作。除了CRUD外,还包括如分

    2023年04月19日
    浏览(48)
  • spring Data Elasticsearch入门

    1.Elasticsearch Elasticsearch提供了两种连接方式: transport:通过TCP方式访问ES。(已废弃) rest:通过HTTP API 方式访问ES。 描述: Spring Data Elasticsearch 项目提供了与Elasticsearch 搜索引擎的集成。Spring Data ElasticSearch 的关键功能领域是以POJO为中心的模型,用于与Elastichsearch 文档交互并

    2024年02月02日
    浏览(53)
  • Spring Data Elasticsearch介绍(七)

            Spring Data Elasticsearch是Spring Boot套件中的一个组件,在Spring Boot中连接ES可以使用Spring Data Elasticsearch。         Spring Data Elasticsearch是Spring Data项目的一部分,该项目致力于提供一致的基于Spring的数据查询和存储编程模型。         Spring Data Elasticsearch封装了创

    2024年02月14日
    浏览(49)
  • 6.5 Elasticsearch(五)Spring Data Elasticsearch - 增删改查API

    可以访问spring官网查看其API的具体使用方式:https://docs.spring.io/spring-data/elasticsearch/docs/current/reference/html/#reference Spring Data Elasticsearch 是 Elasticsearch 搜索引擎开发的解决方案。它提供了模板对象,用于存储、搜索、排序文档和构建聚合的高级API。 例如, Repository 使开发者能够通

    2024年02月04日
    浏览(46)
  • Elasticsearch Java客户端和Spring data elasticsearch-Elasticsearch文章三

    https://www.elastic.co/cn/ 整合springboot看上一篇文章 一定要对应好版本,Elasticsearch 的不同版本变化是真大, https://docs.spring.io/spring-data/elasticsearch/docs/4.4.10/reference/html/ Springboot: 2.7.10 spring-data-elasticsearch: 4.4.10 spring-boot-starter-data-elasticsearch: 2.7.10 elasticsearch-java: 7.17.9 https://github.com/

    2024年02月14日
    浏览(43)
  • Spring Data Elasticsearch 的简单使用

    目录 一、简介 二、配置 三、映射 四、 常用方法 五、操作(重点) 1、对索引表的操作 2、对文档的操作(重点) (1)、添加文档  (2)、删除文档 (3)、查询文档(重点) 查询全部文档 (两种方式) matchQuery根据拆分进行全局搜索 matchPhraseQuery短语搜索--完整搜

    2024年02月12日
    浏览(43)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包