How to structure and search with array of dates

Hi. I’m building an index of “Items”. An “Item” can have multiple dates. The dates are defined by “month” and “year”.

So Item X can have the dates “03-2018” and “01-2017”

I would want to structure and search this item in a way that If I search for the month “03”, year “2018” or both, Item X would appear but if I search for “03” AND “2017” it wont

I have tried doing a “dates” attribute with an array of dates formatted as “03-2018” “01-2017” and have also tried by doing an array of nested objects like

dates: [
{
'month': 03,
'year': 2018
}, 
{
'month': 01,
'year': 2017
},
]

I’m using PHP/Laravel to build this application. I’m only missing this issue with the dates. Thanks

Hi,

Algolia, for performances reasons and by design, can’t search on a specific nested object of an array without searching in the others objects of this array. But you can easily change your date format to something like:

{
    "dates: ["2017-03", "2017-01"]
}

And in this case, you’ll be able to search: "filters": "date:2017-03" in your query.
You can also use a numeric timestamp and filter with the numeric operators > >= < <=.

For example:

{
    "dates": [1496275200,1517529600]
}

and then, if you want all dates between 2017 and 2018: "filters": "dates > 1483228800 AND dates < 1514764800"

I hope it’s will help,
Arnaud.

Hi! Thank you for your response. How about if I want just Items in “2017” or just items in monnth “03”. How would you handle that?

Hi there, absent the full use-case, I can give a suggestion to get the specific outcome you described.

You can try to split the same object into multiple objects. Instead of one, you will have two:

{
    "item": "MyItemWithTwoDates",
    "dates": [
    {
      "month": 1,
      "year": 2017
    }
  ],
  "objectID": "MyFirstObject"
}

{
   "item": "MyItemWithTwoDates",  
   "dates": [
    {
      "month": 3,
      "year": 2018
    }
  ],
  "objectID": "MySecondObject"
}

Then you can disable type tolerance on dates.year (otherwise, “2017” will still be just 1-typo away from “2018” and return relevant results")

Using the above, you can then see that searching for “3 2017” will return 0 hits:

The solution based on the timestamp also allow you to get all news from 2017:
"filters": "dates > 1483228800 AND dates < 1514764800"

Or all news only for March to June 2018:
"filters": "dates > 1519862400 AND dates < 1525132800"

Or just March 2018:
"filters": "dates > 1519862400 AND dates < 1522540800

It’s the solution we use on my company to manage every dates in Algolia (Very handy cause we can have very specific filters, allow us to make some very flexibles “Range filters”:
Group

You can use it combined to another field containing a more “human date” to be able to search the year in a text query.

1 Like