Skip to content

Instantly share code, notes, and snippets.

@russcam
Created January 23, 2017 23:01
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 russcam/c77ec26fd1f2e4980c46ba8ee2f91243 to your computer and use it in GitHub Desktop.
Save russcam/c77ec26fd1f2e4980c46ba8ee2f91243 to your computer and use it in GitHub Desktop.
Working with Fields in NEST 5.0.1
void Main()
{
var pool = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));
var connectionSettings = new ConnectionSettings(pool);
var client = new ElasticClient(connectionSettings);
/**
All the following produce the query json
{
"query": {
"query_string": {
"query": "search for this in post title, body, comments and tags",
"fields": [
"title",
"body",
"comments",
"tags"
]
}
}
}
*/
// 1. use expressions for fields
var fields = new Field[]
{
Infer.Field<Post>(f => f.Title),
Infer.Field<Post>(f => f.Body),
Infer.Field<Post>(f => f.Comments),
Infer.Field<Post>(f => f.Tags)
};
var searchResponse = client.Search<Post>(m => m
.Query(q => q
.QueryString(qs => qs
.Fields(f => f
.Fields(fields)
)
.Query("search for this in post title, body, comments and tags")
)
)
);
// 2. Use strings for fields
fields = new Field[]
{
"title",
"body",
"comments",
"tags"
};
searchResponse = client.Search<Post>(m => m
.Query(q => q
.QueryString(qs => qs
.Fields(f => f
.Fields(fields)
)
.Query("search for this in post title, body, comments and tags")
)
)
);
// 3. Loop inside .Fields to add fields
var fieldExpressions = new Expression<Func<Post, object>>[]
{
f => f.Title,
f => f.Body,
f => f.Comments,
f => f.Tags
};
searchResponse = client.Search<Post>(m => m
.Query(q => q
.QueryString(qs => qs
.Fields(f =>
{
foreach (var field in fieldExpressions)
f.Field(field);
return f;
})
.Query("search for this in post title, body, comments and tags")
)
)
);
// 4. use the Object Initializer syntax to build a searchrequest instance
var searchRequest = new SearchRequest<Post>
{
Query = new QueryStringQuery
{
Fields = new []
{
Infer.Field<Post>(f => f.Title),
Infer.Field<Post>(f => f.Body),
Infer.Field<Post>(f => f.Comments),
Infer.Field<Post>(f => f.Tags)
},
Query = "search for this in post title, body, comments and tags"
}
};
searchResponse = client.Search<Post>(searchRequest);
}
public class Post
{
public string Title { get; set; }
public string Body { get; set; }
public IEnumerable<string> Comments { get; set; }
public IEnumerable<string> Tags { get; set; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment