I am trying to use the NEST APIs to execute a search. In my logic of building this up with the fluent api I need to do a conditional check and so far I have this however I believe my assignment will be getting overwritten. Is there a recommended way to do this type of thing?
var d = new SearchDescriptor<AuditLog>();
d = d.Query(q => q
.Bool(b => b
.Filter(bf => bf
.DateRange(r => r
.Field(f => f.UtcDateTime)
.GreaterThanOrEquals(message.UtcFrom)
.LessThanOrEquals(message.UtcTo)
)
).Filter(fg => fg.Terms(descriptor => descriptor.Field(f => f.AccessControlid).Terms(aclIds)))
)
);
if (message.CustomerId != -1)
{
d = d.Query(q => q.Bool(kk => kk.Must(must => must.Match(m => m.Field(c => c.AuditUserId).Query("2")))));
}
var resp = this.elasticClient.Search<AuditLog>(s =>
{
s = d;
return s
.Index(ElasticIndex.AuditLog)
.Size(20)
.From(message.Offset);
});
Your query looks fine. Pretty much all NEST fluent API calls are assignative, so last assignment wins. I think may be one or two places in the API where a call is additive, but this should be considered a bug.
resp = client.Search<AuditLog>(s => s
.Query(q =>
{
QueryContainer c = +q.DateRange(r => r
.Field(f => f.UtcDateTime)
.GreaterThanOrEquals(message.UtcFrom)
.LessThanOrEquals(message.UtcTo)
) &&
+q.Terms(r => r.Field(f => f.AccessControlid).Terms(aclIds));
if (message.CustomerId != -1)
c = c && +q.Terms(r => r.Field(f => f.AuditUserId).Terms(userIds));
return c;
})
.Index("audit_log")
.Size(20)
.From(message.Offset)
);
This takes advantage of unary + operator overloading to specify a bool query filter clause, and combining them with binary && operator.
With the following
var now = DateTime.UtcNow;
var message = new Message
{
CustomerId = 10,
UtcFrom = now.AddMonths(-1),
UtcTo = now,
};
var aclIds = new []{"acl1", "acl2"};
var userIds = new []{"user1", "user2"};
Apache, Apache Lucene, Apache Hadoop, Hadoop, HDFS and the yellow elephant
logo are trademarks of the
Apache Software Foundation
in the United States and/or other countries.