I am reading the docs for Key generation in app engine. I'm not sure what effect using a simple String key has over a real Key. For example, when my users sign up, they must supply a unique username:
class User {
/** Key type = unencoded string. */
#PrimaryKey
private String name;
}
now if I understand the docs correctly, I should still be able to generate named keys and entity groups using this, right?:
// Find an instance of this entity:
User user = pm.findObjectById(User.class, "myusername");
// Create a new obj and put it in same entity group:
Key key = new KeyFactory.Builder(
User.class.getSimpleName(), "myusername")
.addChild(Goat.class.getSimpleName(), "baa").getKey();
Goat goat = new Goat();
goat.setKey(key);
pm.makePersistent(goat);
the Goat instance should now be in the same entity group as that User, right? I mean there's no problem with leaving the User's primary key as just the raw String?
Is there a performance benefit to using a Key though? Should I update to:
class User {
/** Key type = unencoded string. */
#PrimaryKey
private Key key;
}
// Generate like:
Key key = KeyFactory.createKey(
User.class.getSimpleName(),
"myusername");
user.setKey(key);
it's almost the same thing, I'd still just be generating the Key using the unique username anyway,
Thanks
When you specify a string key as you are in your example, you're specifying a key name (see the docs). As such, you shouldn't be using the KeyFactory - simply set the key field as 'myusername'.
There's no performance difference between the two options, though: Internally they are stored identically; the key name is just easier to use if you're not using parent entities for this model.
Related
Say, I want to save/create new item to the DynamoDb table,
if and only if there is not any existent item already that that would contain the referenceId equal to the same value I set.
In my case I want to create a item with withReferenceId=123 if there is not any other withReferenceId=123 in the table.
the referenceId is not primary key! (I don not want it to be it)
So the code:
val withReferenceIdValue = "123";
val saveExpression = new DynamoDBSaveExpression();
final Map<String, ExpectedAttributeValue> expectedNoReferenceIdFound = new HashMap();
expectedNoReferenceIdFound.put(
"referenceId",
new ExpectedAttributeValue(new AttributeValue().withS(withReferenceIdValue)).withComparisonOperator(ComparisonOperator.NE)
);
saveExpression.setExpected(expectedNoReferenceIdFound);
newItemRecord.setReferenceId(withReferenceId);
this.mapper.save(newItemRecord, saveExpression); // do not fail..
That seems does not work.
I the table has the referenceId=123 already the save() does not fail.
I expected this.mapper.save to fail with exception.
Q: How to make it fail on condition?
I also checked this one where they suggest to add auxiliary table (transaction-state table)..because seems the saveExpression works only for primary/partition key... if so:
not sure why there that limitation. in any case if it is primary key
one can not create duplicated item with the same primary key.. why
creating conditions on first place. 3rd table is too much.. why there
is not just NE to whatever field I want to use. I may create an index
for this filed. not being limited to use only primary key.. that what
I mean
UPDATE:
My table mapping code:
#Data // I use [lombok][2] and it does generate getters and setters.
#DynamoDBTable(tableName = "MyTable")
public class MyTable {
#DynamoDBHashKey(attributeName = "myTableID")
#DynamoDBAutoGeneratedKey
private String myTableID;
#DynamoDBAttribute(attributeName = "referenceId")
private String referenceId;
#DynamoDBAttribute(attributeName = "startTime")
private String startTime;
#DynamoDBAttribute(attributeName = "endTime")
private String endTime;
...
}
Correct me if I'm wrong, but from the:
https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/dynamodb-dg.pdf
Conditional Writes By default, the DynamoDB write operations (PutItem,
UpdateItem, DeleteItem) are unconditional: each of these operations
will overwrite an existing item that has the specified primary key
the primary key - that makes me thing that the conditional write works ONLY with primary keys
--
Also there is attempt use the transactional way r/w from the db. There is a library. That event has not maven repo: https://github.com/awslabs/dynamodb-transactions
As an alternative seems is the way to use 3rd transaction table with the primary keys that are responsible to tell you whether you are ok to read or write to the table. (ugly) as we replied here: DynamoDBMapper save item only if unique
Another alternative, I guess (by design): it is to design your tables in a way so you use the primary key as your business-key, so you can use it for the conditional writes.
--
Another option: use Aurora :)
--
Another options (investigating): https://aws.amazon.com/blogs/database/building-distributed-locks-with-the-dynamodb-lock-client/ - this I do not like either. because potentially it would create timeouts for others who would want to create new items in this table.
--
Another option: Live with this let duplication happens for the item-creation (not including the primary key). And take care of it as a part of "garbage collection". Depends on the scenario.
Is a key value mandatory while setting up an EntityType?
This may sound a little odd but I have a case where a key is unnecessary. So I was asking myself if I can get rid of these code lines.
List<PropertyRef> keyProperties = new ArrayList<PropertyRef>();
keyProperties.add(new PropertyRef().setName("KEY"));
Key key = new Key().setKeys(keyProperties);
A key is required for an entityType in olingo and odata, because if there is no unique key for an entity then we won't be able to use getEntity (to query the data of just one entity from a given entitySet) on it , as well as navigation properties and $expand will also not behave properly.
each user can have many questions. questions can only have one user. is the following correct
Key questionKey = KeyFactory.createKey("Questions", userId);
Entity questionEntity = new Entity("Question", questionKey);
questionEntity.setProperty("questionCategory", questionCategory);
...
The given usage is wrong. For the question, you are creating key using kind and userid . This implies the corresponding entity is of Kind="Questions" and id=userid and no parents. This is wrong and you will start getting errors once you have more than 1 question for a user as they will all have the same key.
Ideally what you need is that for a question entity, declare its kind as question and parent as the user as follows :
1, If using manually generated id or name for a question , then :
Key questionKey = KeyFactory.createKey(userkey, "Questions", questionidorname);
2, If using app engine's auto generate id, then no need create key, instead create entity as:
Entity questionEntity = new Entity("Questions",
userkey)
Here userkey is the key of a user entity
I am using Google App Engine with the Datastore interface.
Whenever I'm trying to update an entity, a whole new entity is created, this is despite the fact that I'm positive I am saving the same entity, meaning it has the same key for sure.
This is my code:
Key key=KeyFactory.createKey("user",Long.parseLong(ID));
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
Entity entity=new Entity("user",key);
entity.setProperty // ...whatever, updating the properties
datastore.put(entity); //by putting an entity it's supposed to
// either create a new one if non exists, or update an entity if it already exists
I am sure that the key is the same during all updates as is confirmed in my admin console:
id=3001 600643316
id=3002 600643316
id=3003 600643316
a bunch of entities with the same key (600643316) is created.
The datastore only lets the app create a new entity with a String key name, not a numeric ID. Numeric IDs are system-assigned IDs. If the Key has a numeric ID but not a String key name, then the datastore will ignore it and replace it with a system-assigned numeric ID.
In your example, if ID is a string, then you can just remove the Long.parseLong() bit, or convert it back to a String. KeyFactory.createKey(String kind, String name) creates a Key with a key name.
So it seems Dan is correct and this is the correct way to do it , as explained in google's guides if you want your app to build keys from unique keys that you create you need to use strings .
"You specify whether an entity ought to use an app-assigned key name string or a system-assigned numeric ID as its identifier when you create the object. To set a key name, provide it as the second argument to the Entity constructor:
Entity employee = new Entity("Employee","asalieri");" It seems you're correct , in their example the second argument is indeed a string – user1032663
I'm just getting started with MongoDb and I've noticed that I get a lot of duplicate records for entries that I meant to be unique. I would like to know how to use a composite key for my data and I'm looking for information on how to create them. Lastly, I am using Java to access mongo and morphia as my ORM layer so including those in your answers would be awesome.
Morphia: http://code.google.com/p/morphia/
You can use objects for the _id field as well. The _id field is always unique. That way you kind of get a composite primary key:
{ _id : { a : 1, b: 1} }
Just be careful when creating these ids that the order of keys (a and b in the example) matters, if you swap them around, it is considered a different object.
The other possibility is to leave _id alone and create a unique compound index.
db.things.ensureIndex({firstname: 1, lastname: 1}, {unique: true});
//Deprecated since version 3.0.0, is now an alias for db.things.createIndex()
https://docs.mongodb.org/v3.0/reference/method/db.collection.ensureIndex/
You can create Unique Indexes on the fields of the document that you'd want to test uniqueness on. They can be composite as well (called compound key indexes in MongoDB land), as you can see from the documentation. Morphia does have a #Indexed annotation to support indexing at the field level. In addition with morphia you can define compound keys at the class level with the #Indexed annotation.
I just noticed that the question is marked as "java", so you'd want to do something like:
final BasicDBObject id = new BasicDBObject("a", aVal)
.append("b", bVal)
.append("c", cVal);
results = coll.find(new BasicDBObject("_id", id));
I use Morphia too, but have found (that while it works) it generates lots of errors as it tries to marshall the composite key. I use the above when querying to avoid these errors.
My original code (which also works):
final ProbId key = new ProbId(srcText, srcLang, destLang);
final QueryImpl<Probabilities> query = ds.createQuery(Probabilities.class)
.field("id").equal(key);
Probabilities probs = (Probabilities) query.get();
My ProbId class is annotated as #Entity(noClassnameStored = true) and inside the Probabilities class, the id field is #Id ProbId id;
I will try to explain with an example:
Create a table Music
Add Artist as a primary key
Now since artist may have many songs we have to figure out a sort key.
The combination of both will be a composite key.
Meaning, the Artist + SongTitle will be unique.
something like this:
{
"Artist" : {"s" : "David Bowie"},
"SongTitle" : {"s" : "changes"},
"AlbumTitle" : {"s" : "Hunky"},
"Genre" : {"s" : "Rock"},
}
Artist key above is: Partition Key
SongTitle key above is: sort key
The combination of both is always unique or should be unique. Rest are attributes which may vary per record.
Once you have this data structure in place you can easily append and scan as per your custom queries.
Sample Mongo queries for reference:
db.products.insert(json file path)
db.collection.drop(json file path)
db.users.find(json file path)