Elasticsearch 查询超过10000 的解决方案 - Python

这篇具有很好参考价值的文章主要介绍了Elasticsearch 查询超过10000 的解决方案 - Python。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

Elasticsearch 查询超过10000 的解决方案 - Python

法1:修改 设置 max_result_size (不推荐)

# 调大查询窗口大小,比如100w (不推荐,慎用)
PUT test/_settings
{
  "index.max_result_window": "1000000"
}

# 查看 查询最大数
GET test/_settings
---
{
  "demo_scroll" : {
    "settings" : {
      "index" : {
        "number_of_shards" : "5",
        "provided_name" : "demo_scroll",
        "max_result_window" : "1000000",
        "creation_date" : "1680832840425",
        "number_of_replicas" : "1",
        "uuid" : "OLV5W_D9R-WBUaZ_QbGeWA",
        "version" : {
          "created" : "6082399"
        }
      }
    }
  }
}

法2: scroll 分页

    def getData(self):
        current_time = datetime.datetime.now()
        one_hour_ago = current_time - datetime.timedelta(hours=24)
        current_time_str = current_time.strftime('%Y-%m-%d %H:%M:%S')
        hours_ago_str = one_hour_ago.strftime('%Y-%m-%d %H:%M:%S')

        # 改为从elasticsearch读取数据
        es = Elasticsearch(hosts='http://127.0.0.1/9200',
                           timeout=1200)
        size = 10000
        query_scroll = {
            "size": size,
            "query": {
                "range": {
                    "create_time.keyword": {
                        "gte": hours_ago_str.__str__(),
                        "lte": current_time_str.__str__()
                    }
                }
            },
            "_source": ["ip_address", "OS", "host", "user", "create_time"],
        }
        scroll = "10m" # 该次连接超时时间设置
        result = []
        # first
        init_res = es.search(index="nac-users", body=query_scroll, scroll=scroll)
        scroll_id = init_res["_scroll_id"]
        for item in init_res["hits"]["hits"]:
            result.append({
                'id': item['_id'],
                'ip_address': item['_source']['ip_address'],
                'operating_system': item['_source']['OS'],
                'hostname': item['_source']['host'],
                'username': item['_source']['user'],
                'date_t': item['_source']['create_time'],
            })
        i = 0
        while i < 16:  # 剩下的数据 一天 24 小时数据估计不会超过 160000
            res = es.scroll(scroll_id=scroll_id, scroll=scroll)
            if len(res["hits"]["hits"]) == 0:
                break
            for item in res["hits"]["hits"]:
                result.append({
                    'id': item['_id'],
                    'ip_address': item['_source']['ip_address'],
                    'operating_system': item['_source']['OS'],
                    'hostname': item['_source']['host'],
                    'username': item['_source']['user'],
                    'date_t': item['_source']['create_time'],
                })
            i = i + 1
            
        # 原始的    
        # {"query": {"match_all": {}}, "size": 10000}
        # res = es.search(index="nac-users", body=query_scroll)
        #
        # result = []
        # for item in res['hits']['hits']:
        #     result.append({
        #         'id': item['_id'],
        #         'ip_address': item['_source']['ip_address'],
        #         'operating_system': item['_source']['OS'],
        #         'hostname': item['_source']['host'],
        #         'username': item['_source']['user'],
        #         'date_t': item['_source']['create_time'],
        #     })
        self.data = pd.DataFrame(result)

法3: search_after 分页

def getData(self):
      current_time = datetime.datetime.now()
      one_hour_ago = current_time - datetime.timedelta(hours=24)
      current_time_str = current_time.strftime('%Y-%m-%d %H:%M:%S')
      hours_ago_str = one_hour_ago.strftime('%Y-%m-%d %H:%M:%S')

      # 改为从elasticsearch读取数据
      es = Elasticsearch(hosts='http://127.0.0.1:9200',
                         timeout=1200)
      size = 10000
      query_scroll = {
          "size": size,
          "query": {
              "range": {
                  "create_time.keyword": {
                      "gte": hours_ago_str.__str__(),
                      "lte": current_time_str.__str__()
                  }
              }
          },
          "sort": [
              {
                  "create_time.keyword": {
                      "order": "desc"
                  }
              }
          ],
          "_source": ["ip_address", "OS", "host", "user", "create_time"],
      }
      result = []
      init_res = es.search(index="nac-users", body=query_scroll)
      if len(init_res["hits"]["hits"]) == 0:
          self.data = pd.DataFrame(result)
          return
      sort = init_res["hits"]["hits"][0]["sort"] # 我这里是用时间来排序的,所以取到的是时间字段
      for item in init_res["hits"]["hits"]:
          result.append({
              'id': item['_id'],
              'ip_address': item['_source']['ip_address'],
              'operating_system': item['_source']['OS'],
              'hostname': item['_source']['host'],
              'username': item['_source']['user'],
              'date_t': item['_source']['create_time'],
          })
      i = 0
      while i < 16:
          query_scroll["search_after"] = sort
          res = es.search(index="nac-users", body=query_scroll)
          sort = res["hits"]["hits"][0]["sort"]
          if len(res["hits"]["hits"]) == 0:
              break
          for item in res["hits"]["hits"]:
              result.append({
                  'id': item['_id'],
                  'ip_address': item['_source']['ip_address'],
                  'operating_system': item['_source']['OS'],
                  'hostname': item['_source']['host'],
                  'username': item['_source']['user'],
                  'date_t': item['_source']['create_time'],
              })
          i = i + 1
    self.data = pd.DataFrame(result)        

还有一个方法是在参考文章2里面提到的track_total_hits,但是我测试的时候没起作用,目前还不太清楚原因。。。

我看参考文章里说到search_after 分页要比scroll快,但是在我的数据上是scroll要快很多,不是特别清楚,可能我这里的数据暂时只有2w多一点,感觉用到search_after 分页需要排序,可能是排序的字段的问题,时间字段我存的是字符串格式,,如有可以修改的地方,欢迎大家指正~ 有更多可以参考的方法欢迎贴在评论区供大家参考~

【参考1】https://juejin.cn/post/7224369270141993019
【参考2】https://blog.csdn.net/u011250186/article/details/125483759文章来源地址https://www.toymoban.com/news/detail-817517.html

到了这里,关于Elasticsearch 查询超过10000 的解决方案 - Python的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

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

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

相关文章

  • es解决只能默认查询10000条数据方案

    在使用es进行数据查询时,由于es官方默认限制了索引一次性最多只能查询10000条数据,这其实是es的一种保护机制,那么很多时候我们需要突破这种限制,例如需要进入数据同步的场景,则需要查询全部的数据,如何处理呢? 方案1:在设置索引属性时解除索引最大查询数的限

    2024年02月11日
    浏览(31)
  • 如何解决elasticsearch分页总数量超过10000条就报错

    默认情况下,Elasticsearch集群中每个分片的搜索结果数量限制为10000。这是为了避免潜在的性能问题。具体报错信息如下: 但是,可以通过以下几种方法解决这个问题。 1. 使用scroll API:scroll API可以帮助我们在不加载所有数据的情况下获取所有结果。它会在后台执行查询以获取

    2024年02月17日
    浏览(39)
  • elasticsearch查询异常解决方案

    {\\\"error\\\":{\\\"root_cause\\\":[{\\\"type\\\":\\\"security_exception\\\",\\\"reason\\\":\\\"missing authentication token for REST request [/]\\\",\\\"header\\\":{\\\"WWW-Authenticate\\\":\\\"Basic realm=\\\"security\\\" charset=\\\"UTF-8\\\"\\\"}}],\\\"type\\\":\\\"security_exception\\\",\\\"reason\\\":\\\"missing authentication token for REST request [/]\\\",\\\"header\\\":{\\\"WWW-Authenticate\\\":\\\"Basic realm=\\\"security\\\" charset=\\\"UTF-8\\\"\\\"}},\\\"sta

    2024年02月16日
    浏览(30)
  • Graylog日志查询超过10000限制问题

    在使用graylog时,默认分页查询存在限制,真实使用不能满足,需要我们手动处理。当查询超过执行长度时,会出现一下错误提示 问题描述 查询超过 10000 页, Elasticsearch 出现异常 解决方案 方案一:修改配置文件,重启 Elasticsearch 服务【 Elasticsearch5.x 版本以后不支持】 修改

    2024年02月04日
    浏览(36)
  • [解决方案]基于Elasticsearch 为电商提供商品数据大数据查询

    对于现代电商的产品,维度的多员花,与一套强大的搜索引擎,那是非常必要的。今天我们主要是描述我们在从事电商搜索引擎过程中的遇到的一些问题和经验分享。 1、我们准备为我们需要做查找的数据做好一张视图,方便我们分析数据查找维度,与查找场景需求。附加代

    2024年02月09日
    浏览(34)
  • ElasticSearch - DSL查询文档语法,以及深度分页问题、解决方案

    目录 一、DSL 查询文档语法 前言 1.1、DSL Query 基本语法 1.2、全文检索查询 1.2.1、match 查询 1.2.2、multi_match 1.3、精确查询 1.3.1、term 查询 1.3.2、range 查询 1.4、地理查询 1.4.1、geo_bounding_box 1.4.2、geo_distance 1.5、复合查询 1.5.1、相关性算分 1.5.2、function_score 1.5.3、boolean query 1.6、搜索

    2024年02月07日
    浏览(39)
  • Elasticsearch 8.X 聚合查询下的精度问题及其解决方案

    咕泡同学提问:我在看runtime文档的时候做个测试, agg求avg的时候不管是double还是long,数据都不准确,这种在生产环境中如何解决啊? 上述问题可以归类为:Elasticsearch聚合查询下的 精度 问题。 在日常的数据处理工作中,我们经常会遇到使用Elasticsearch进行大数据查询、统计

    2024年02月16日
    浏览(25)
  • Elasticsearch 7 以上版本显示hits.total超过10000条设置

    添加rest_total_hits_as_int=true即可   需要在sql里面添加  /*! TRACK_TOTAL_HITS(true) */ 或者用 /*! TRACK_TOTAL_HITS(10001) */ 直接限制记录数量查询即可  请求地址 http://172.21.72.165:9200/_nlpcn/sql 请求头 Content-Type:application/json Authorization:Basic ZWxhc3RpYzoxMjM0NTY= 请求入参 {     \\\"sql\\\": \\\"select /*! TRACK_TO

    2024年02月03日
    浏览(29)
  • SQL拦截:想要限制每次查询的结果集不能超过10000行,该如何实现?

    实践出真知,欢迎关注我的公众号:Hoeller 对于一些Saas化软件,当某个租户在执行查询SQL时,如果查询条件出现了BUG,导致去查了所有租户的数据,这种情况是非常严重的,此时就需要在架构层面做限制,禁止一些特殊SQL的执行,另外,为了保护数据库,也可能会限制某些查

    2024年02月05日
    浏览(29)
  • Elasticsearch分页搜索数量不能超过10000的解决This limit can be set by changing the [index.max_result_window] index

    开发环境:  JDK1.8、Elasticsearch7.3.1、RestHighLevelClient 问题:  最近在通过Java客户端操作ES进行分页查询(from+size)时,分页获取满足条件的数据和总数。发现满足条件的数据总数一旦超过10000条,使用SearchResponse的getHits().getTotalHits().value返回的结果永远是10000。为什么会被限制只能搜

    2024年02月04日
    浏览(28)

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

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

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

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

二维码1

领取红包

二维码2

领红包