How to get latest document from specific date?

坚强是说给别人听的谎言 提交于 2019-12-13 03:39:45

问题


I'm trying to get the latest document from specified date (variable) in Couchbase and N1QL on a very large database (150 millions documents each month). The latest document from a date could be any time (previous second or last month). Note, the date is in Unix Epoch. Here is a structure of the documents:

{
  "type" : "person",
  "id":"001",
  "name":"John Doe",
  "date":"1491199810.435"
}

I have index on date:

CREATE INDEX `date` ON `mytable`(`date`) WITH { "defer_build"=true }

Usually in Postgres that I dealt with, I usually would do:

SELECT * WHERE date <="1491199813.000" ORDER BY date DESC LIMIT 1;

Having index on date in Postgres just flies with response in milliseconds.

However, Couchbase ORDER BY ... LIMIT is very slow. It takes minutes on the same hardware and same data.

Surely there an efficient way of getting single latest document from specified date with Couchbase N1QL, but I can't find it yet.

Would you have any ideas?


回答1:


Create negative functional index and change the query like below In pre 5.0.0

CREATE INDEX `forex_dt` ON `forex`(-TONUMBER(`date`));
SELECT * FROM `forex` WHERE -TONUMBER(`date`) >= -1491199813.000 ORDER BY -TONUMBER(`date`) LIMIT 1;

In 5.0.0

CREATE INDEX `forex_dt` ON `forex`(`date` DESC);
SELECT * FROM `forex` WHERE `date` <= "1491199813.000" ORDER BY `date` DESC LIMIT 1;


来源:https://stackoverflow.com/questions/45777035/how-to-get-latest-document-from-specific-date

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