es搜索引擎 python es搜索引擎java使用

什么是Elasticsearch

在IT界简称ES,但是搜索时(百度时)建议使用Elasticsearch来获得更有效的资源

这个软件不再是SpringCloud提供的,它也不针对微服务环境的项目来开发

Elasticsearch和redis\mysql一样,不仅服务与java语言,其它语言也可以使用

Elasticsearch是java开发的软件,所以启动它需要java环境变量

它的功能也类似一个数据库,能高效的从大量数据中搜索匹配指定关键字的内容

这样的软件有一个名称**全文搜索引擎**

它本质就是一个java项目,使用它进行数据的增删改查就是访问这个项目的控制器方法(url路径)

ES也会将数据保存在硬盘上

> ES的底层技术

ES使用了java的一套名为Lucene的API

这个API提供了全文搜索引擎核心操作的接口,相当于搜索引擎的核心支持,ES是在Lucene的基础上进行的完善,实现了开箱即用的搜索引擎软件

市面上和ES功能类似的软件有

Solr/MongoDB

为什么需要Elasticsearch

数据库进行模糊查询严重低下

所有关系型数据库都有这个缺点(mysql\mariaDB\oracle\DB2等)

在执行类似下面模糊查询时

“`sql
select * from spu where spu_name like ‘%鼠标%’
“`

测试证明**一张千万级别的数据表进行模糊查询需要20秒以上**

当前互联网项目要求”三高”的需求下,这样的效率肯定不能接受

Elasticsearch主要是为了解决数据库模糊查询性能低下问题的

ES进行优化之后,从同样数据量的ES中查询相同条件数据,效率能够提高100倍以上

数据库中索引基本概念

所谓的索引(index)其实就是数据目录

通常情况下,索引是为了提高查询效率的

数据库索引分两大类

* 聚集索引
* 非聚集索引

聚集索引就是数据库保存数据的物理顺序,默认情况下就是主键id,所以按id查询数据库中的数据效率非常高

如果想在非主键列上添加索引,就是非聚集索引了

例如我们在数据库表中存在一个姓名列,我们为姓名列创建索引

在创建索引时,会根据姓名内容来创建索引

例如”张三” 这个姓名,创建索引后查询效率就会明显提升

如果没有索引,这样的查询就会引起效率最低的逐行搜索,就是一行一行的查这个数据的姓名是不是张三

模糊查询时因为’%鼠标%’,使用的是前模糊条件,使用索引必须明确前面的内容是什么,前模糊查询是不能使用索引的,只能是全表的逐行搜索,所以效率非常低

Elasticsearch运行原理

ES软件在保存数据时,和关系型数据库不同

在将数据保存到ES时,可以对指定的列进行分词索引保存在索引库中

形成倒排索引结构

 Elasticsearch的启动

官方下载链接

 https://www.elastic.co/cn/downloads/past-releases#elasticsearch

课程中使用7.6.2的版本

压缩包280M左右,复制到没有中文,没有空格的目录下解压

双击bin\elasticsearch.bat运行

“`
elasticsearch.bat
“`

双击之后可能会看到下面的dos界面

这个界面不能关闭,一旦关闭ES就停止了

验证ES的运行状态

浏览器输入地址:localhost:9200看到如下内容即可

 

ES基本使用

ES启动完成后,我们要学习如何操作它

我们已经讲过,操作ES是对es发送请求

我们创建一个子项目search,在这个子项目中创建一个专门发送各种类型请求的文件来操作ES

创建search项目也要父子相认

然后子项目pom文件如下

复制

```xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>cn.tedu</groupId>
        <artifactId>csmall</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>cn.tedu</groupId>
    <artifactId>search</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>search</name>
    <description>Demo project for Spring Boot</description>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
    </dependencies>
</project>
     
 
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.

删除test文件夹

下面创建一个能够向ES发送请求的文件

这种能够向指定url发送请求的文件格式称之为http client(http 客户端)

文件类型叫HTTP Request文件

我们先从最简单的请求开始

向es发送指令

复制

```json
GET http://localhost:9200
### 三个#既是分隔符也是注释,两个请求之间必须使用它来分割,否则无法运行
POST http://localhost:9200/_analyze
Content-Type: application/json
{
  "text": "罗技激光鼠标",
  "analyzer": "standard"
}
     
 
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.

analyze:分析

analyzer:分析者(分词器)

standard是ES默认的分词器,”analyzer”: “standard”是可以省略的

standard这个分词器只能对英文等西文字符(有空格的),进行正确分词

但是中文分词不能按空格分,按这个分词器分词,每个字都会形成分词,这样的结果不能满足我们日常的搜索需要

 

我们解决中文不能正确分词的问题

实际上要引入一个中文常见词语的词库,分词时按照词库中的词语分词即可

我们可以使用免费的中文分词器词库插件IK来实现中文分词效果

 

安装插件之后要重启ES才能生效

关闭Es窗口之后再双击运行即可

ES启动之后,将中文分词器插件设置完成,在运行分词

复制

```json
{
  "text": "罗技激光无线游戏鼠标",
  "analyzer": "ik_smart"
}
```
     
 
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.

再次运行分词测试,应该看到正常的中文分词效果

ik分词插件的使用

我们安装的ik实际上不只一个分词器

实际上除了ik_smart之外还有ik_max_word

复制

```json
POST http://localhost:9200/_analyze
Content-Type: application/json
{
  "text": "北京成功举行了冬季奥林匹克运动会",
  "analyzer": "ik_smart"
}
```
```json
POST http://localhost:9200/_analyze
Content-Type: application/json
{
  "text": "北京成功举行了冬季奥林匹克运动会",
  "analyzer": "ik_max_word"
}
     
 
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.

上面的两个分词器运行分词,结果会有非常明显的区别

总结区别如下

**ik_smart**

* 优点:特征是粗略快速的将文字进行分词,占用空间小,查询速度快

* 缺点:分词的颗粒度大,可能跳过一些重要分词,导致查询结果不全面,查全率低

**ik_max_word**

* 优点:特征是详细的文字片段进行分词,查询时查全率高,不容易遗漏数据
* 缺点:因为分词太过详细,导致有一些无用分词,占用空间较大,查询速度慢

使用ES操作数据

ES是一个数据库性质的软件

可以执行增删改查操作

我们先了解一下ES保存数据的结构

 

* ES启动后,ES服务可以创建多个index(索引),index可以理解为数据库中表的概念

* 一个index可以创建多个保存数据的document(文档),一个document理解为数据库中的一行数据
* 一个document中可以保存多个属性和属性值,对应数据库中的字段(列)和字段值

Spring Data简介

原生状态下,我们使用JDBC连接数据库,因为代码过于繁琐,所以改为使用Mybatis框架

在ES的原生状态下,我们java代码需要使用socket访问ES,但是也是过于繁琐,我们可以使用SpringData框架简化

Spring Data是Spring提供的一套连接各种第三方数据源的框架集

我们需要使用的是其中连接ES的Spring Data Elasticseatrch

官方网站:https://spring.io/projects/spring-data

官网中列出了SpringData支持连接操作的数据源列表

下面我们就按照SpringDataElasticsearch的步骤对ES进行操作

添加依赖和配置

search模块的pom文件添加依赖

复制

```xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>cn.tedu</groupId>
        <artifactId>csmall</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>cn.tedu</groupId>
    <artifactId>search</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>search</name>
    <description>Demo project for Spring Boot</description>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
        <!--  SpringDataElasticsearch的依赖  -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        </dependency>
    </dependencies>
</project>
     
 
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.

application.properties添加配置

复制

```properties
# 设置ES所在的ip地址和端口号信息
spring.elasticsearch.rest.uris=http://localhost:9200
# 设置日志门槛,显示ES运行信息
logging.level.cn.tedu.search=debug
# SpringDataES底层一个源码类,也有日志信息的输出,单独设置
logging.level.org.elasticsearch.client.RestClient=debug
```
     
 
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.

创建和ES关联的实体类

和数据库一样

我们操作ES时也需要一个类似实体类的数据类,作为操作ES的数据载体

search项目创建entity包

在包中创建Item(商品)类

复制

```java
@Data
@Accessors(chain = true)     // 支持链式set赋值功能
@AllArgsConstructor          // 自动生成包含全部参数的构造方法
@NoArgsConstructor           // 自动生成无参构造方法
// @Document是SpringDataES标记实体类的注解
// indexName指定关联的索引名称,运行时如果items索引不存在,SpringData会自动将它创建出来
@Document(indexName = "items")
public class Item implements Serializable {
    // SpringData标记当前属性为ES的主键
    @Id
    private Long id;
    // SpringData标记title属性是text类型支持分词的,以及分词器
    @Field(type = FieldType.Text,
                    analyzer = "ik_max_word",
                    searchAnalyzer = "ik_max_word")
    private String title;       // 商品名称
    // Keyword类型是不需要分词的字符串类型
    @Field(type = FieldType.Keyword)
    private String category;    // 商品分类
    @Field(type = FieldType.Keyword)
    private String brand;       // 品牌
    @Field(type = FieldType.Double)
    private Double price;       // 价格
    //  图片地址不会成为搜索条件,所以设置index = false
    //  这样ES就不会为它创建索引库了,能够节省空间
    @Field(type = FieldType.Keyword,index = false)
    private String imgPath;     // 图片地址
    // images/1a123s-as4td-asdsa-jasbdjff.png
}
     
 
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.

创建操作ES的持久层

我们使用SpringData连接ES

需要使用SpringData框架对持久层的命名规则

持久层规范名称为repository(仓库),创建这个包,包中创建接口ItemRepository

复制

```java
// Spring 家族持久层命名规范为repository
@Repository
public interface ItemRepository extends ElasticsearchRepository<Item,Long> {
    // 当前ItemRepository接口可以继承SpringDataElasticsearch框架提供的父接口ElasticsearchRepository
    // 一旦继承,效果是会为指定的实体类自动生成基本的增删改查方法
    // ElasticsearchRepository<[关联的实体类名],[实体类主键类型]>
     
 
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.

测试ES

创建测试类

编写测试

复制

```java
@SpringBootTest
public class SearchTest {
    // 装备ItemRepository接口实现类对象
    @Autowired
    private ItemRepository itemRepository;
    // 单增
    @Test
    void addOne(){
        // 实例化一个Item对象完成新增
        Item item=new Item()
                .setId(1L)
                .setTitle("罗技激光无线游戏鼠标")
                .setCategory("鼠标")
                .setBrand("罗技")
                .setPrice(168.0)
                .setImgPath("/1.jpg");
        // 利用SpringDataES提供的方法完成新增操作
        itemRepository.save(item);
        System.out.println("ok");
    }
    //  单查
    @Test
    void getOne(){
        // SpringDataES提供了按id查询ES中数据的方法
        // Optional是一个类似包装类的概念,查询的结果封装到了这个类型的对象中
        Optional<Item> optional= itemRepository.findById(1L);
        //Item i= itemRepository.findById(1L).get();
        System.out.println(optional.get());
    }
    // 批量增
    @Test
    void addList(){
        // 实例化一个List对象
        List<Item> list=new ArrayList<>();
        // 将要新增的对象保存到List中
        list.add(new Item(2L,"罗技激光有线办公鼠标","鼠标",
                "罗技",88.0,"/2.jpg"));
    list.add(new Item(3L,"雷蛇机械无线游戏键盘","键盘",
            "雷蛇",299.0,"/3.jpg"));

    list.add(new Item(4L,"微软有线静音办公鼠标","鼠标",
            "微软",205.0,"/4.jpg"));

    list.add(new Item(5L,"罗技有线机械背光键盘","键盘",
            "罗技",266.0,"/5.jpg"));
    itemRepository.saveAll(list);
    System.out.println("ok list");
}
// 全查
@Test
void getAll(){
    // 利用SpringDataES的方法实现对Es的全查
    Iterable&lt;Item&gt; items= itemRepository.findAll();
    for(Item item: items){
        System.out.println(item);
    }
    items.forEach(item -&gt; System.out.println(item));
}

}

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.
  • 65.
  • 66.
  • 67.
  • 68.

SpringData自定义查询

SpringData框架提供的基本增删改查方法并不能完全满足我们的业务需要

如果是针对当前Es数据,进行个性化的自定义查询,那还是需要自己编写查询代码

就像我们要实现根据关键词查询商品信息一样,完成类似数据库中的模糊查询

单条件查询

我们查询需求为输出所有数据中title属性包含”游戏”这个分词的商品信息

> 参考数据库中模糊查询
>
> sql<br> &gt; select * from item where title like '%游戏%'<br> &gt;

我们使用SpringDataES进行查询,本质上还是相当于ES文档中执行的查询语句

在SpringData框架下,ItemRepository接口中实现更加简单

复制

java // SpringData自定义查询 // 遵循SpringData框架给定的格式,编写方法名称,就可以自动生成查询语句 // query(查询): 表示当前方法是一个查询方法,类似sql中的select // Item\Items: 表示要查询的实体类,不带s返回单个对象,带s返回集合类型 // By(通过): 标识开始设置条件的关键词,类似sql中的where // Title: 要查询的字段名称 // Matches: 执行的查询操作,Matches表示执行查询支持分词的字符串 类似sql中的like Iterable&lt;Item&gt; queryItemsByTitleMatches(String title);</code><ul class="pre-numbering" style=""><li>1.</li><li>2.</li><li>3.</li><li>4.</li><li>5.</li><li>6.</li><li>7.</li><li>8.</li><li>9.</li><li>10.</li></ul></pre></div><div class="toolbar"></div></div></div><p>下面可以开始在测试类中进行测试查询</p><div><div class="code-toolbar"><div class="hljs-cto"><div class="operation_box"><button data-clipboard-target="#code_id_10" class="copy_btn copy10">复制</button> <a title="一键下载全文代码" class="downloadCode"><i class="iconblog blogimport "></i></a> </div><pre class="language-plain prettyprint" tabindex="0"><code class="language-plain has-numbering" id="code_id_10">java
// 单条件查询
@Test
void queryOne(){
// 查询ES数据中title包含"游戏"分词的数据
Iterable<Item> items=itemRepository.queryItemsByTitleMatches("游戏");
items.forEach(item -> System.out.println(item));
}
</code><ul class="pre-numbering" style=""><li>1.</li><li>2.</li><li>3.</li><li>4.</li><li>5.</li><li>6.</li><li>7.</li><li>8.</li><li>9.</li></ul></pre></div><div class="toolbar"></div></div></div><p>上面代码运行时底层运行的查询语句为:</p><h3 id="h16">单条件搜索</h3><div><div class="code-toolbar"><div class="hljs-cto"><div class="operation_box"><button data-clipboard-target="#code_id_11" class="copy_btn copy11">复制</button> <a title="一键下载全文代码" class="downloadCode"><i class="iconblog blogimport "></i></a> </div><pre class="language-plain prettyprint" tabindex="0"><code class="language-plain has-numbering" id="code_id_11">js

单条件搜索

POST http://localhost:9200/items/_search
Content-Type: application/json
{
"query": {"match": { "title": "游戏" }}
}
</code><ul class="pre-numbering" style=""><li>1.</li><li>2.</li><li>3.</li><li>4.</li><li>5.</li><li>6.</li><li>7.</li><li>8.</li><li>9.</li></ul></pre></div><div class="toolbar"></div></div></div><h3 id="h17">多条件查询</h3><p>在相对复杂的查询逻辑下</p><p>经常使用多个条件来定位查询需要的数据</p><p>这样就需要逻辑运算符"and"/"or"</p><p>ItemRepository接口中添加多条件的查询方法</p><div><div class="code-toolbar"><div class="hljs-cto"><div class="operation_box"><button data-clipboard-target="#code_id_12" class="copy_btn copy12">复制</button> <a title="一键下载全文代码" class="downloadCode"><i class="iconblog blogimport "></i></a> </div><pre class="language-plain prettyprint" tabindex="0"><code class="language-plain has-numbering" id="code_id_12">java
// 多条件查询
// 多个条件之间需要使用逻辑运算符And或Or来分割
// 方法参数赋值的依据是根据方法名称中参数的顺序来决定的
Iterable<Item> queryItemsByTitleMatchesAndBrandMatches(String title,String brand);
</code><ul class="pre-numbering" style=""><li>1.</li><li>2.</li><li>3.</li><li>4.</li><li>5.</li><li>6.</li><li>7.</li></ul></pre></div><div class="toolbar"></div></div></div><p>测试代码如下</p><div><div class="code-toolbar"><div class="hljs-cto"><div class="operation_box"><button data-clipboard-target="#code_id_13" class="copy_btn copy13">复制</button> <a title="一键下载全文代码" class="downloadCode"><i class="iconblog blogimport "></i></a> </div><pre class="language-plain prettyprint" tabindex="0"><code class="language-plain has-numbering" id="code_id_13">java
// 多条件查询
@Test
void queryTwo(){
// 查询ES数据中title包含"游戏"并且品牌是"雷蛇"的数据
Iterable<Item> items=itemRepository.
queryItemsByTitleMatchesAndBrandMatches("游戏","雷蛇");
items.forEach(item -> System.out.println(item));
}
</code><ul class="pre-numbering" style=""><li>1.</li><li>2.</li><li>3.</li><li>4.</li><li>5.</li><li>6.</li><li>7.</li><li>8.</li><li>9.</li><li>10.</li><li>11.</li></ul></pre></div><div class="toolbar"></div></div></div><p>底层运行的请求</p><div><div class="code-toolbar"><div class="hljs-cto"><div class="operation_box"><button data-clipboard-target="#code_id_14" class="copy_btn copy14">复制</button> <a title="一键下载全文代码" class="downloadCode"><i class="iconblog blogimport "></i></a> </div><pre class="language-plain prettyprint" tabindex="0"><code class="language-plain has-numbering" id="code_id_14">js

多字段搜索

POST http://localhost:9200/items/_search
Content-Type: application/json
{
"query": {
"bool": {
"must": [
{ "match": { "title": "游戏"}},
{ "match": { "brand": "雷蛇"}}
]
}
}
}

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.

当查询条件关系为And时,查询语句关键字为must

当查询条件关系为Or时,查询语句关键字为should

排序查询

在ItemRepository接口添加具备排序功能的查询方法

复制

```java
// 排序查询
Iterable<Item>
queryItemsByTitleMatchesOrBrandMatchesOrderByPriceDesc(
String title,String brand);

测试
```java
// 排序查询
@Test
void queryOrder(){
    Iterable&lt;Item&gt; items=
            itemRepository.queryItemsByTitleMatchesOrBrandMatchesOrderByPriceDesc(
                    "游戏","罗技");
    items.forEach(item -&gt; System.out.println(item));
}

底层运行的代码

### 多字段搜索
POST http://localhost:9200/items/_search
Content-Type: application/json
{
  "query": {
    "bool": {
      "should": [
        { "match": { "title": "游戏"}},
        { "match": { "brand": "罗技"}}
      ]
    }
  },"sort":[{"price":"desc"}]
}</code><ul class="pre-numbering" style=""><li>1.</li><li>2.</li><li>3.</li><li>4.</li><li>5.</li><li>6.</li><li>7.</li><li>8.</li><li>9.</li><li>10.</li><li>11.</li><li>12.</li><li>13.</li><li>14.</li><li>15.</li><li>16.</li><li>17.</li><li>18.</li><li>19.</li><li>20.</li><li>21.</li><li>22.</li><li>23.</li><li>24.</li><li>25.</li><li>26.</li><li>27.</li><li>28.</li><li>29.</li><li>30.</li><li>31.</li><li>32.</li><li>33.</li><li>34.</li><li>35.</li><li>36.</li><li>37.</li></ul></pre></div><div class="toolbar"></div></div></div><h3 id="h19">分页查询</h3><p>SpringData框架支持完成分页查询</p><p>需要在ItemRepository接口中修改方法的参数和返回值就可以实现</p><div><div class="code-toolbar"><div class="hljs-cto"><div class="operation_box"><button data-clipboard-target="#code_id_16" class="copy_btn  copy16">复制</button> <a title="一键下载全文代码" class="downloadCode"><i class="iconblog blogimport  "></i></a> </div><pre class="language-plain prettyprint" tabindex="0"><code class="language-plain has-numbering" id="code_id_16">```java
// 分页查询
// 实现分页查询:最后一个参数的位置添加声明类型Pageable的变量
// 返回值修改为Page类型,这个类型的对象不但能够保存查询出的数据,而且还能自动计算出分页信息
// 分页信息中包括:当前页,总页数,总条数,是否有上一页或下一页等
Page&lt;Item&gt; queryItemsByTitleMatchesOrBrandMatchesOrderByPriceDesc(
        String title, String brand, Pageable pageable);

测试代码如下

// 分页查询
@Test
void queryPage(){
    int pageNum= 1;  // 页码
    int pageSize=2;  // 每页条数
    Page&lt;Item&gt; page=itemRepository
            .queryItemsByTitleMatchesOrBrandMatchesOrderByPriceDesc(
                    "游戏","罗技", PageRequest.of(pageNum-1,pageSize));
    page.forEach(item -&gt; System.out.println(item));
    // page中除了查询得到数据还包含分页信息
    System.out.println("总页数:"+page.getTotalPages());
    System.out.println("总条数:"+page.getTotalElements());
    System.out.println("当前页:"+page.getNumber());
    System.out.println("每页条数:"+page.getSize());
    System.out.println("是否为首页:"+page.isFirst());
    System.out.println("是否为末页:"+page.isLast());
}</code><ul class="pre-numbering" style=""><li>1.</li><li>2.</li><li>3.</li><li>4.</li><li>5.</li><li>6.</li><li>7.</li><li>8.</li><li>9.</li><li>10.</li><li>11.</li><li>12.</li><li>13.</li><li>14.</li><li>15.</li><li>16.</li><li>17.</li><li>18.</li><li>19.</li><li>20.</li><li>21.</li><li>22.</li><li>23.</li><li>24.</li><li>25.</li><li>26.</li><li>27.</li><li>28.</li><li>29.</li></ul></pre></div><div class="toolbar"></div></div></div></div>
原文链接:https://blog.51cto.com/u_16099346/6751282

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。