问题
I’m trying to create an index that returns sorted data in an object with keys. The default index for my collection returns something like this:
{
"ref": Ref(Collection("posts"), "251333584234742292"),
"ts": 1583632773120000,
"data": {
"title": "A Great Title",
"sort_date": "2019-12-11",
"post_type": "blog",
"status": "published",
}
},...
I created an index in the shell with this code:
CreateIndex({
name: "posts_sort_date_desc",
source: Collection("posts"),
values: [
{ field: ["data", "sort_date"], reverse: true },
{ field: ["data", "title"] },
{ field: ["data", "post_type"] },
{ field: ["data", "status"] },
{ field: ["ref"] }
]
}
When I look at this new index, the sorting is correct, but it looks like an array of arrays with no keys like this:
[
"2019-12-11",
"A Great Title",
"",
"published",
Ref(Collection("posts"), "254000373213168147")
], ...
Is there a way to create a sorted index with only the data that I need with key value pairs? I’ve looked through the docs but can’t figure it out. Thanks.
回答1:
the short answer to your question is: "no there is not", but there are probably solutions to your problem (I'll need to better understand the problem you try to solve). Indexes will always return arrays of data since that's how they are structured and FaunaDB provides you access to the raw power of the index. We do not try to be clever and interpret what you might want.
(Disclaimer, I didn't test the code, it's 11:30 pm here so I'm almost going to log off :) but still wanted to help you)
That said, there are two options:
- Instead of basing yourself on the values from your index, take out the ref and write a Map/Get to get the underlying document, that one will come as an object. Each Get though also costs a read so that's a tradeoff to make, it will however be much more flexible when new attributes are added that you don't want to sort on but do want to return (else you'll have to recreate the index).
Map(
Paginate(Match(Index('your_index_name'))),
Lambda(['sort_date', 'title', 'post_type', 'status', 'ref'], Get(Var('ref')))
)
- Keep the index as is, and once you get these values you can easily write a Map (in FQL) over these index pages and restructure the result by returning an Object. This would look something like
Map(
Paginate(Match(Index('your_index_name'))),
Lambda(['sort_date', 'title', 'post_type', 'status', 'ref'],
{
ref: Var('ref'),
sort_date: Var('sort_date'),
title: Var('title'),
post_type: Var('post_type'),
status: Var('status')
}
)
)
That should give you an array of objects instead :)
来源:https://stackoverflow.com/questions/62602964/how-do-i-create-an-index-in-fauna-db-that-returns-sorted-data-in-key-value-pairs