Scroll example in ElasticSearch NEST API

后端 未结 3 2093
故里飘歌
故里飘歌 2020-12-31 10:06

I am using .From() and .Size() methods to retrieve all documents from Elastic Search results.

Below is sample example -



        
3条回答
  •  [愿得一人]
    2020-12-31 10:39

    Internal implementation of NEST Reindex uses scroll to move documents from one index to another.

    It should be good starting point.

    Below you can find interesting for you code from github.

    var page = 0;
    var searchResult = this.CurrentClient.Search(
        s => s
            .Index(fromIndex)
            .AllTypes()
            .From(0)
            .Size(size)
            .Query(this._reindexDescriptor._QuerySelector ?? (q=>q.MatchAll()))
            .SearchType(SearchType.Scan)
            .Scroll(scroll)
        );
    if (searchResult.Total <= 0)
        throw new ReindexException(searchResult.ConnectionStatus, "index " + fromIndex + " has no documents!");
    IBulkResponse indexResult = null;
    do
    {
        var result = searchResult;
        searchResult = this.CurrentClient.Scroll(s => s
            .Scroll(scroll)
            .ScrollId(result.ScrollId)
        );
        if (searchResult.Documents.HasAny())
            indexResult = this.IndexSearchResults(searchResult, observer, toIndex, page);
        page++;
    } while (searchResult.IsValid && indexResult != null && indexResult.IsValid && searchResult.Documents.HasAny());
    

    Also you can take a look at integration test for Scroll

    [Test]
    public void SearchTypeScan()
    {
        var scanResults = this.Client.Search(s => s
            .From(0)
            .Size(1)
            .MatchAll()
            .Fields(f => f.Name)
            .SearchType(SearchType.Scan)
            .Scroll("2s")
        );
        Assert.True(scanResults.IsValid);
        Assert.False(scanResults.FieldSelections.Any());
        Assert.IsNotNullOrEmpty(scanResults.ScrollId);
    
        var results = this.Client.Scroll(s=>s
            .Scroll("4s") 
            .ScrollId(scanResults.ScrollId)
        );
        var hitCount = results.Hits.Count();
        while (results.FieldSelections.Any())
        {
            Assert.True(results.IsValid);
            Assert.True(results.FieldSelections.Any());
            Assert.IsNotNullOrEmpty(results.ScrollId);
            var localResults = results;
            results = this.Client.Scroll(s=>s
                .Scroll("4s")
                .ScrollId(localResults.ScrollId));
            hitCount += results.Hits.Count();
        }
        Assert.AreEqual(scanResults.Total, hitCount);
    }
    

提交回复
热议问题