Gordo
Gordo

Reputation: 83

Searching by list of date ranges in elastic search

I'm working on a system which needs to select valid days from an arbitrary schedule.

I want to be able to use a list of DateRanges as my search request, but I'm unsure as to how to actually do this effectively in elastic NEST.

Here is a bit of example code for what I'm trying to do effectively.

// my list of date ranges
var dateQuery = new List<DateRangeQuery>();

// make query foreach day
foreach (var day in valid_days)
{
    dateQuery.Add(new DateRangeQuery
    {
        Field = "Date",
        GreaterThanOrEqualTo = day.Item1, // DateTime start of day tuple
        LessThanOrEqualTo = day.Item2 // DateTime end of day tuple
    });
}

// query by list of search request           
var search = new SearchRequest
{
    // how do i use a list of date time's here?
    Query = dateQuery;
}

var example = _client.Search(search);

EDIT:

Solved using this code, thanks for the assistance!

Note: the NEST API is quite confusing, if you don't know the DSL syntax.

var dateQuery = new QueryContainer();

// make date range query from valid day list
foreach (var day in daylist)
{
    // x = x || y
    dateQuery = dateQuery || new DateRangeQuery
    {
        Field = "date",
        GreaterThanOrEqualTo = day.Item1, // start of day
        LessThanOrEqualTo = day.Item2 // end of day
    };
}

// match by query
var search = _client.Search(
    s => s.Query(
        q => && q.Bool(b => b.Should(dateQuery)));

Spoke to elastic, they are wanting to make the NEST API simpler for C# devs in future too, so watch this space.

All the selectors feels like too much bloat in the code.

I've used the || operator instead of | because || has performance benefits if your expression is evaluated and hits a match, it returns sooner.

Hope this helps anyone looking for it.

Upvotes: 3

Views: 1331

Answers (1)

swapnil2993
swapnil2993

Reputation: 1394

I guess you need to use bool query with must for multiple range queries. Something like

{
"query": {
    "bool": {
        "must": [
            {
                "range": {
                    "created_at": {
                        "gte": "2013-12-09T00:00:00.000Z"
                    }
                }
            },
            {
                "range": {
                    "happens_on": {
                        "lte": "2013-12-16T00:00:00.000Z"
                    }
                }
            }
        ]
    }
 }
}

In the .Net client I think you can use QueryContainer. Please refer this link as I am not that familiar with .Net client of elasticsearch.

Upvotes: 1

Related Questions