How to add Timestamps to Data Objects in Weaviate and then Sort by Time

Connor Shorten
2 min readSep 27, 2022

Hey everyone, I wanted to just quickly document this in case someone else finds themself working on a similar problem.

Step 1 — Set a date property in Weaviate

{
"dataType": ["date"],
"name": "timeEntered",
"description": "The time this object entered Weaviate."
}

Step 2 — (If uploading in Python, timestamp the objects like this)

from datetime import datetime
# we could be looping through data items and put this in that loop
# here is how to do it for one objectdatetime_now = datetime.now()
rfcc = datetime_now.strftime("%Y-%m-%dT%H:%M:%S+00:00")
client.data_object.create(
data_object = { "timeEntered": rfcc }
)

Step 3 — Sort Data objects with these timestamps (GraphQL)

{
Get {
TimeObj (
sort: [{
path: ["timeEntered"],
order: desc
}]
){
idx
timeEntered
}
}
}

Here is a dummy example of setting this up to then run the query in Step 3

import weaviateclient = weaviate.Client("http://localhost:8080")schema = {
"classes": [
{
"class": "TimeObj",
"description": "A time object test.",
"properties": [
{
"dataType": ["date"],
"name": "timeEntered",
"description": "The time this data object was added to Weaviate."
},
{
"dataType": ["int"],
"name": "idx",
"description": "idx used to test the time sorting"
}
]
}
]
}
client.schema.create(schema)from datetime import datetime, timezone
import time
from weaviate.util import generate_uuid5
for x in range(5):
datetime_now = datetime.now()
datetime_now = datetime_now.strftime("%Y-%m-%dT%H:%M:%S+00:00")
client.data_object.create(
data_object = {
"timeEntered": datetime_now,
"idx": x
},
uuid = generate_uuid5(x),
class_name = "TimeObj"
)
time.sleep(2)

After running that you can execute the query in Step 3 to see Weaviate sorting by timestamp in action. You can get a docker-compose script for a locally hosted Weaviate here — https://weaviate.io/developers/weaviate/current/installation/docker-compose.html.

Anyways I hope this was useful, I know this isn’t a proper blog post but I would have liked to stumble upon something like this an hour ago while working on something else, so hopefully someone else finds value. Again, lazily documented so please feel free to leave a comment where something needs clarification.

Photo by Sabri Tuzcu on Unsplash

--

--