Search code examples
azure-cognitive-searchazure-search-.net-sdk

Azure Cognitive Search: Facet "values" for DateTime field


I think I'm not understanding to do what I want. I want to offer a list of facets that look like this:

  • Created Today (123)
  • Created in the last week (3,455)
  • Created in the last month (12,234)
  • Created in the last year (112,234)

The documents say ""facet=lastRenovationDate,values:2010-02-01T00:00:00Z" produces two buckets: one for hotels renovated before February 2010, and one for hotels renovated February 1, 2010 or later.

Logically, I'm not understanding how to create these buckets. There's no documentation explaining how to offer ranges of dates, and I can't figure out the right combo.

I can figure out the code, but logically how would I accomplish the above? Thanks!


Solution

  • Assumptions

    Assuming your field that you want to facet on is createdDate and is of type Edm.DateTimeOffset. For your requirement, I think there will be some calculations that you'd have to do after you get the facet data back.

    These are the dates you are interested in

    (today) - 2021-08-12T00:00:00Z

    yesterday - (today - 1 day) 2021-08-11T00:00:00Z

    last week - (yesterday - 1 week) 2021-08-04T00:00:00Z

    last month - (4 weeks back to 1 weeks back) 2021-07-12T00:00:00Z

    last year - (1 year ago to last month) 2020-08-12T00:00:00Z

    Query and Response

    so you will specify 4 values in your facet - yesterday, last week, last month, last year. I will first use these names in the actual query to make it more readable. The second is the actual query you will make

    1. human readable query - facet=createdDate,values:last year | last month | last week | yesterday
    2. actual search query - facet=createdDate,values:2020-08-12T00:00:00Z| 2021-07-12T00:00:00Z | 2021-08-04T00:00:00Z | 2021-08-11T00:00:00Z

    This will result in 5 buckets of data as follows.

    a - everything older than last year (you don't need this, you can throw it away)

    b - everything from last year to last month

    c - everything from last month to last week

    d - everythng from last week to yesterday

    e - everything from yesterday to today

    Solution

    Now the following will be the calculations in order to get the ranges you need.

    • Created Today (123) - e

    • Created in the last week (3,455) - d + e

    • Created in the last month (12,234) - c + d + e

    • Created in the last year (112,234) - b + c + d + e

    • Created prior to last year (547,838) - a