Skip to content

Instantly share code, notes, and snippets.

@Yegoroff
Created June 28, 2013 23:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Yegoroff/5888926 to your computer and use it in GitHub Desktop.
Save Yegoroff/5888926 to your computer and use it in GitHub Desktop.
using System;
using PlainElastic.Net;
using PlainElastic.Net.Queries;
using PlainElastic.Net.Serialization;
namespace PlainElasticScrolling
{
class Program
{
static void Main()
{
var connection = new ElasticConnection("localhost", 9200);
var serializer = new JsonNetSerializer();
// Add a sample documents to index.
for (int i = 1; i <= 100; i++)
{
var note = new Note {Caption = "Test Note " + i, Text = "Note to test scrolling"};
string noteJson = serializer.ToJson(note);
connection.Put(Commands.Index("notes", "note", i.ToString()), noteJson);
}
// Create query to scroll.
string query = new QueryBuilder<Note>()
.Query(q => q
.MatchAll()
)
.Size(1) // Note: actual hits count per each scroll request will be "Size" multiplied by the number of primary shards. (e.g. 1 * 5 shards = 5)
.BuildBeautified();
Console.WriteLine("QUERY: \r\n" + query);
// Execute scroll query with 5m keep alive time.
string results = connection.Post(Commands.Search("notes", "note").Scroll("5m").SearchType(SearchType.scan), query);
var scrollResults = serializer.ToSearchResult<Note>(results);
// Get the initial scroll ID
string scrollId = scrollResults._scroll_id;
Console.WriteLine("\r\nScrolling results: \r\n");
do
{
// Execute SearchScroll request to scroll found documents.
results = connection.Get(Commands.SearchScroll(scrollId).Scroll("5m"));
scrollResults = serializer.ToSearchResult<Note>(results);
foreach (var note in scrollResults.Documents)
Console.WriteLine(note.Caption);
// Update scroll ID
scrollId = scrollResults._scroll_id;
// We should wait till no hits has been returned to stop scrolling.
} while (scrollResults.hits.hits.Length > 0);
Console.WriteLine("\r\nDone");
Console.ReadKey();
}
}
public class Note
{
public string Caption { get; set; }
public string Text { get; set; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment