如何进行分页弹性搜索?

Hul*_*ula 4 php elasticsearch

我是弹性搜索的新手。

我尝试制作真正的应用程序。我正在使用 elasticsearch-php
https://github.com/elastic/elasticsearch-php

我不知道要分页。

我的代码:

<?php
require_once 'app/init.php';

if(isset ($_GET['q'])) {

  $q = $_GET['q'];

  $query = $es->search([
    'index' => 'user',
    'type' => 'profile',
    'body' => [
      'query' => [
        'bool' => [
          'should' => [
            'match' => ['bio' => $q]
            ]
        ]
    ]
]
  ]);
  if ($query['hits']['total'] >=1) {
    $results= $query['hits']['hits'];
  }

}

 ?>

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Search | ES</title>
  </head>
  <body>
    <form class="" action="index.php" method="get" autocomplete="off">
      <label for="">
          Search
          <input type="text" name="q">
      </label>
      <input type="submit" value="search">
    </form>
    <?php
      if (isset($results)) {
        foreach ($results as $r) {
      ?>
          <div class="result">
            <?php echo $r['_source']['bio']; ?>
          </div>
     <?php
        }
      }
     ?>
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

以及如何进行这样的分页:

查看图片 像 github 一样的分页

use*_*217 5

您需要在这里做两件事,总页数和从一页导航到另一页的方式。当您使用 simple 查询 elasticsearch 时Query->filter->bool

它在响应 JSON 中返回命中,这是结果的总数。将它们除以您要在应用程序上显示的结果数量,您将获得页面。

在 PHP-elasticsearch 请求对象中使用 from 和 size 属性,并在页面之间导航时更改不断变化。示例查询(考虑第 3 页和页面大小 10)

{
    "from": 20,
    "size": 10,
    "query": {
        "bool": {
            "must": [
                {
                    "term": {
                        "FIELD": {
                            "value": "VALUE"
                        }
                    }
                }
            ]
        }
    }
}
Run Code Online (Sandbox Code Playgroud)