问题
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