es分页from+size,scroll,search_after

当使用Elasticsearch进行分页查询时,from+size方式在数据超过1万条后无法获取更多数据。本文通过示例介绍了如何利用scroll API和search_after参数来实现高效的数据分页,确保能获取到存储的所有source信息。
摘要由CSDN通过智能技术生成

es分页用from+size的方式超过1万条就查不出数据了。

查询大于1万的数据这里使用scroll和go-elasiticsearch简单写一个demo

package main

import (
	"bytes"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
	"strconv"
	"strings"
	"sync"
	"time"

	"github.com/elastic/go-elasticsearch/v8"
	"github.com/tidwall/gjson"
)

var c *elasticsearch.Client
var once sync.Once

func main() {
	log.SetFlags(0) //这里设置的0即取消log格式化输出,输出的内容和使用fmt包下的println()格式一样

	var (
		batchNum int
		scrollID string
	)

	es := setElastic([]string{"http://ip:9200"})

	// Index 100 documents into the "test-scroll" index
	//测试写入100个document
	log.Println("Indexing the documents...")
	for i := 1; i <= 100; i++ {
		res, err := es.Index(
			"test-scroll",
			strings.NewReader(`{"title" : "test"}`),
			es.Index.WithDocumentID(strconv.Itoa(i)),
		)
		if err != nil || res.IsError() {
			log.Fatalf("Error: %s: %s", err, res)
		}
	}
	es.Indices.Refresh(es.Indices.Refresh.WithIndex("test-scroll"))

	// Perform the initial search request to get
	// the first batch of data and the scroll ID
	//
	log.Println("Scrolling the index...")
	log.Println(strings.Repeat("-", 80))
	res, _ := es.Search(
		es.Search.WithIndex("test-scroll"),
		es.Search.WithSort("_doc"),
		es.Search.WithSize(10),
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用elasticsearch的Java客户端restHighLevelClient实现search_after + PIT分页,可以按照以下步骤进行操作: 1. 创建SearchRequest对象,设置index、type、source等属性。 2. 使用SearchSourceBuilder设置查询条件,包括查询关键字、过滤条件、排序规则等。 3. 创建SearchCursor对象,使用SearchCursor.scroll方法进行第一次查询,并获取SearchAfterBuilder对象。 4. 使用SearchAfterBuilder设置search_after参数,并使用SearchCursor.scroll方法进行下一查询。 5. 重复步骤4直到查询到最后一数据。 下面是具体代码实现: ```java // 创建SearchRequest对象 SearchRequest searchRequest = new SearchRequest(index); searchRequest.types(type); // 创建SearchSourceBuilder对象 SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); sourceBuilder.query(QueryBuilders.matchQuery("field", "value")); sourceBuilder.sort(SortBuilders.fieldSort("date").order(SortOrder.DESC)); sourceBuilder.from(0).size(10); // 设置每显示10条数据 // 创建SearchCursor对象 SearchCursor cursor = new SearchCursor(searchRequest, sourceBuilder, client); // 第一次查询并获取SearchAfterBuilder对象 SearchAfterBuilder searchAfterBuilder = cursor.scroll(); // 循环查询下一数据 while (searchAfterBuilder != null) { // 设置search_after参数 sourceBuilder.searchAfter(searchAfterBuilder.getSearchAfter()); // 查询下一数据 SearchResponse response = client.search(searchRequest.source(sourceBuilder)); // 处理查询结果 processResponse(response); // 获取下一SearchAfterBuilder对象,如果返回null则表示查询到最后一数据 searchAfterBuilder = cursor.scroll(response); } ``` 使用PIT分页可以避免查询过程中数据的变化对查询结果的影响,具体实现方法可以参考elasticsearch官方文档。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值