Skip to content

Instantly share code, notes, and snippets.

@lindstromhenrik
Created September 19, 2017 02: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 lindstromhenrik/3ea5b96da2321e214d20e5cb57de49a1 to your computer and use it in GitHub Desktop.
Save lindstromhenrik/3ea5b96da2321e214d20e5cb57de49a1 to your computer and use it in GitHub Desktop.
NestPercolation
using Nest;
using System;
using System.Collections.Generic;
using System.Linq;
namespace NestPercolation
{
class Program
{
static void Main(string[] args)
{
// Setup/Cleanup
//
var connectionSettings = new ConnectionSettings(); // localhost:9200
connectionSettings.DefaultIndex("default");
var client = new ElasticClient(connectionSettings);
if (client.IndexExists("default").Exists)
{
client.DeleteIndex("default");
}
// Create index mapping (explicit peroclator type mapping for PercolatorDocument.Query)
//
var createIndexResult = client.CreateIndex("default", c =>
c.Mappings(ms => ms
.Map<PercolatorDocument>(m =>m
.AutoMap()
.Properties(ps => ps
.Percolator(p =>
p.Name(d => d.Query)
)
)
)
)
);
// Index PercolatorDocument(s)
//
var percolatorDocumentMathingHenrik = new PercolatorDocument
{
Name = "Match documents matching 'Henrik'",
Query = Query<Document>.Match(m => m
.Field(f => f.Name)
.Query("Henrik"))
};
var percolatorDocumentNotMathingHenrik = new PercolatorDocument
{
Name = "Match documents not matching 'Henrik'",
Query = !Query<Document>.Match(m => m
.Field(f => f.Name)
.Query("Henrik"))
};
var bulkResult = client.Bulk(b => b
.IndexMany(new List<PercolatorDocument> { percolatorDocumentMathingHenrik, percolatorDocumentNotMathingHenrik })
.Refresh(Elasticsearch.Net.Refresh.WaitFor)
);
// Execute percolate query for any PercolatorDocument(s) matching a sample Document
//
var sampleDocument = new Document
{
Name = "My name is Henrik"
};
var percolateSearch = client.Search<PercolatorDocument>(s => s
.Query(q => q
.Percolate(p => p
.DocumentType<Document>()
.Field(Infer.Field<PercolatorDocument>(f => f.Query))
.Document(sampleDocument)
)
)
);
Console.WriteLine("Matching percolators: " + String.Join(", ", percolateSearch.Documents.Select(s => s.Name)));
Console.ReadLine();
}
}
public class Document
{
public string Name { get; set; }
}
public class PercolatorDocument
{
public string Name { get; set; }
public QueryContainer Query { get; set; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment