Reputation: 490
I have a database containing multiple docs. Each doc has a field of user_id. Assuming these docs belong to two users: 1 and 2. I would like to extract one latest doc only for each user. How should I implement the search index? I now can get a user's all docs by using: user_id:1 But how can I limit doc number to one for each user in one query?
Upvotes: 0
Views: 46
Reputation: 3501
Assuming you have a date property on each doc you could accomplish this as follows:
Create the following index:
{
"index": {
"fields": [
{"user_id":"desc"},
{"date_field":"desc"}
]
},
"type": "json"
}
To query for the latest doc for user_id
== "1" your query would look like this:
{
"selector": {
"user_id": "1"
},
"fields": [
"_id",
"user_id",
"date_field"
],
"sort": [
{ "user_id": "desc" },
{ "date_field": "desc" }
],
"limit":1
}
If you are trying to return multiple users in a single query then you would have to do something like this:
latest
or similarAdd an index on user_id
and latest
:
{
"index": {
"fields": [
"user_id",
"latest"
]
},
"type": "json"
}
Whenever you add a new document find the document for that user_id
where latest
is true:
{
"selector": {
"user_id": "1",
"latest" : true
},
"fields": [
"_id",
"user_id",
"latest"
]
}
Set latest
= false on that document
latest
= trueThis query will find the latest doc for all users:
{
"selector": {
"user_id": {"$gt":null},
"latest" : true
},
"fields": [
"_id",
"user_id",
"latest"
]
}
Upvotes: 0