Created
September 19, 2017 02:30
-
-
Save lindstromhenrik/3ea5b96da2321e214d20e5cb57de49a1 to your computer and use it in GitHub Desktop.
NestPercolation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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