Reputation: 1541
I'm new to this nuget package and confused with the Key class.
Here is my code base on Google.Cloud.Datastore.V1 document:
public long InsertMessage<T>(T iEntity) where T : IEntity<T>
{
var keyFactory = _db.CreateKeyFactory(Kind);
var entity = iEntity.ToEntity();
entity.Key = keyFactory.CreateIncompleteKey();
using (var transaction = _db.BeginTransaction())
{
transaction.Insert(entity);
var commitResponse = transaction.Commit();
var insertedKey = commitResponse.MutationResults[0].Key;
Logger.Info($"Inserted key: {insertedKey}");
return insertedKey.Path[0].Id;
}
}
All I do is to create an entity and create an incomplete key, send to the server, then get the populated key back from server.
I think the key is served as unique identity to the entity.
If there's misunderstanding please correct me.
I can get entities by Query as below:
var query = new Query(Kind)
{
Filter = Filter.Equal("key", key),
Order = { { "created", PropertyOrder.Types.Direction.Ascending } }
};
foreach (var entity in _db.RunQueryLazily(query))
{
list.Add(entity);
}
But I don't know how to use the key I got when inserted to get the unique entity by Filter.Equal("key", key)
.
The example shows the Key's structure is:
{
"partitionId":
{
"projectId": "projectId",
"namespaceId": "namespaceId"
},
"path": [
{
"kind": "kind",
"id": "id"
}]
}
Here I conclude the question I have:
id
the unique key to the entity?Query
by Key
and Id
?Thanks for reading and please don't mind my poor English.
Upvotes: 0
Views: 433
Reputation: 1504172
A key is a unique identifier for a document. The documentation says it best:
Each entity in Cloud Datastore has a key that uniquely identifies it. The key consists of the following components:
- The namespace of the entity, which allows for multitenancy
- The kind of the entity, which categorizes it for the purpose of Cloud Datastore queries
- An identifier for the individual entity, which can be either
- a key name string
- an integer numeric ID
- An optional ancestor path locating the entity within the Cloud Datastore hierarchy An optional ancestor path locating the entity within the Cloud Datastore hierarchy
The "ancestor path" part is the reason there's an array in the Path
property - a fully qualified key is a namespace followed by a sequence of path elements, each of which consists of a kind and "integer ID" or "string name" part.
So for example, you might have a library application. That has shelves and books. Ignoring the namespace part, a particular book might have an ID with path elements of:
Another way of thinking of this is like an alternating sequence of collection and document names, e.g. "/shelves/1/books/xyz". That's how Firestore represents its document IDs.
Any one path element doesn't have to be unique, but the complete path is unique. There's no real concept of querying by "key and ID" - you can look up a complete key (e.g. DatastoreDb.Lookup
) or include a parent key as an ancestor path query.
Upvotes: 2