elasticsearch搜索引擎的常用方法(三) 查找10000条数据之后的数据

问题:

     es本身默认限制了查找的量为10000条,即 from+size<=10000

报错:

Result window is too large, from + size must be less than or equal to:[10000] but was [10010]. See the scroll api for a more efficient way to requestlarge data sets. This limit can be set by changing the[index.max_result_window] index level parameter

解决方法:

一、修改es的默认配置

1、 在config/elasticsearch.yml中添加配置

max_result_window: 1000000000

2、 使用api修改index的配置

# 修改es中所有的index配置

PUT _all/_settings
{
  "index":{
    "max_result_window": 1000000000
    
  }
}

注意:

    es也限制了max_result_window的大小,最大为10亿。如果你搜索的量(from+size)大于10亿,请使用方法二

二、使用search_after方法

顾名思义,查找某个点之后的数据,所以需要用from、size、sort、search_after。

实现翻页:search_after本身是无状态的,需要先记录上一次查询的最后一个状态,再从这个状态开始,进行下一次查询,所以也必须又一个统一的排序字段

查询方法:

1、第一次查询语句

# 查询前一万条数据,根据date倒序排列

GET index_1/_search
{
  "from": 0, 
  "size": 10000, 
  "sort": [
    {
      "date": {
        "order": "desc"
      }
    }
  ], 
  "query": {
    "match_all": {}
  }
}

上述语句查询完之后,每一条结果会多出一个“sort”字段,我需要取最后一条数据的sort,即

{
  "took": 1,
  "timed_out": false,
  "_shards": {
    "total": 1,
    "successful": 1,
    "failed": 0
  },
  "hits": {
    "total": 20000,
    "max_score": null,
    "hits": [

    ......

      {
        "_index": "index_1",
        "_type": "type_1",
        "_id": "107686",
        "_score": null,
        "_source": {
          "content": "历史问题我们两个.大小我们增加还有欢迎.一下然后深圳经验.",
          "date": "2019-09-20 13:42:38"
        },
        "sort": [
          1568986958000
        ]
      }
    ]
  }
}

2、第二次查询语句

# 查询1万条之后的10条数据

GET index_1/_search
{
  "from": -1, 
  "size": 10, 
  "sort": [
    {
      "date": {
        "order": "desc"
      }
    }
  ], 
  "search_after":[1568986958000]
}

注意:

    (1)第二次查询基于第一次查询的结果,search_after的值为第一次查询结果的最后一条数据的sort。

    (2)第二次查询的from一定为-1,from+size仍然不能大于10000

    (3)要想实现翻页,需要每次记录最后查询的sort

发布了23 篇原创文章 · 获赞 4 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/Misaki_root/article/details/101203647
今日推荐