how to compare only date part in cosmos db

六月ゝ 毕业季﹏ 提交于 2020-05-27 06:37:05

问题


We are storing (EmployeeId,Name,LogDate) data in cosmosdb. LogDate data is Datetime and we want to get data from cosmos where LogDate between '2018-01-15' and '2018-01-30', Means want to compare date part only.


回答1:


Based on the statements in the official document:

Alternatively, you can store DateTimes as Unix timestamps, that is, as a number representing the number of elapsed seconds since January 1, 1970. Azure Cosmos DB's internal Timestamp (_ts) property follows this approach. You can use the UnixDateTimeConverter class to serialize DateTimes as numbers.

So, I suggest you serializing DateTimes as numbers to compare with the conditions.

You could use User Defined Function in sql:

UDF:

    function convertTime(datetime){
        datetime = datetime.replace(/-/g,'/')  
        if(datetime){
            var date = new Date(datetime);
        }else{
            var date = new Date();
        }
        time1 = date.getTime(); 
        return time1;
    }

SQL:

SELECT c.LogDate FROM c
where udf.convertTime(c.LogDate) > udf.convertTime('2018-01-15') 
and udf.convertTime(c.LogDate) < udf.convertTime('2018-02-20')

Output:

Of course, you could convert the datetime in the code instead of using UDFs.




回答2:


I am from the CosmosDB engineering team. While Jay's answer is an alternative, you could still persist DateTimes as strings in the default ISO 8601 format and create a range index on LogDate. You should be able to do regular comparisons on DateTime like so, using Cosmos DB SQL queries:

SELECT * FROM root where root.LogDate BETWEEN '2018-01-15' and '2018-01-30'



来源:https://stackoverflow.com/questions/54193090/how-to-compare-only-date-part-in-cosmos-db

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!