I am generating Elasticsearch queries for the NEST Client when parsing my own simple query language. That is, the parser returns a QueryDescriptor (which is an alias for Func<QueryContainerDescriptor<SearchResult>, QueryContainer>) which then can be used to get the search results from Elasticsearch.
When the input is a query like nestedObject.someField:someValue, the following method GetQueryDescriptor with query == "nestedObject.someField:someValue" would be invoked.
// NestedObjectQueryToken.cs
public Func<QueryContainerDescriptor<SearchResult>, QueryContainer> GetQueryDescriptor(string query)
{
// GetFieldNames() extracts the fields that the user search in from the query
// (there could possibly be more than one field present)
var nestedFields = query.GetFieldNames().Select(fieldName => new Field("nestedObject." + fieldName));
return descriptor => descriptor.NestedFieldSearch(query, _ => _.Fields(fields));
}
// QueryDescriptorExtensions.cs
public static QueryContainer NestedFieldSearch(this QueryContainerDescriptor<SearchResult> descriptor,
string query, FieldsDescriptor nestedFields)
{
return descriptor.Nested(n => n
.Path("nestedObject")
.Query(sub => sub
.QueryString(queryString => queryString
.Query(query)
.Fields(nestedFields))))
}
SearchResult is the class that is used for the mapping of the results.
The QueryDescriptor is later applied to a SearchDescriptor<SearchResult> so that it can be used in the Search method of NEST.
I expect the QueryDescriptor to have specific properties. In the example above, it should contain a nested query with its inner query's fields set to "nestedObject.someField".
Now I want to test this property with a unit test, i.e. without sending the query to a server.
How can I "look inside the QueryDescriptor" to assert that its properties are as expected?
You can achieve this by casting your result query container to IQueryContainer
QueryContainer Query(QueryContainerDescriptor<Document> q) =>
q.Term(t => t.Field(f => f.Name).Value("something"));
var actual = Query(new QueryContainerDescriptor<Document>()) as IQueryContainer;
Assert.AreEqual("something", actual.Term.Value);
Hope that helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With