GAE JAVA - Getting Object by Property - java

I have Entity say, User { id (primary_key), phone } to be stored in Datastore.
While Retrieving same i can use getObjectById(User.class,id) to get object. Is there way to get object with non-key property, say phone.
As per the documentation, Datastore creates index updates for Property "phone" too.
How do we use this index to get result?

You can simply use a JDO Query like following and Datastore will query on the non-key phone property (assuming you haven't set to to be unindexed).
q = pm.newQuery(User.class,"phone == '1234567890'");

Related

How to get Datastore entity id from com.google.datastore.v1.Entity

I have written a code to fetch data from Google Datastore in my Google Cloud Dataflow program. I am able to fetch all fields of the entity except Id field which is autogenerated field. I have tried to use entity.getKey() but I am getting null.
Below is my code snippet,
Datastore datastore = DataflowDatastoreService.getDatastoreObject(null, null, null);
Query.Builder queryBuilder = Query.newBuilder();
Filter filter1 = Filter.newBuilder()
.setPropertyFilter(PropertyFilter.newBuilder() .setProperty(PropertyReference.newBuilder().setName("cId"))
.setOp(PropertyFilter.Operator.EQUAL)
.setValue(Value.newBuilder().setIntegerValue(1059438885900008L).build()).build()).build();
Filter filter2 = Filter.newBuilder()
.setPropertyFilter(PropertyFilter.newBuilder()
.setProperty(PropertyReference.newBuilder().setName("active"))
.setOp(PropertyFilter.Operator.EQUAL)
.setValue(Value.newBuilder().setBooleanValue(Boolean.TRUE).build()).build()).build();
Filter composeFilter = Filter.newBuilder().setCompositeFilter(CompositeFilter.newBuilder()
.addFilters(filter1).setOp(Operator.AND).addFilters(filter2).build()).build();
queryBuilder.addKind(KindExpression.newBuilder().setName("MyMaster").build());
queryBuilder.setFilter(composeFilter).build();
RunQueryRequest request = DataflowDatastoreService.makeRequest(queryBuilder.build(), null);
RunQueryResponse response = datastore.runQuery(request);
QueryResultBatch batch = response.getBatch();
List<EntityResult> entityResutls = batch.getEntityResultsList();
List<Entity> myEntities = new ArrayList<>();
Map<String, Value> entityMap = myEntities(0).getPropertiesMap();
In my code I am able to get all fields in entityMap key but I am not getting key, is there any other way through which I can fetch all the fields with Id.
Note: I'm not a java user, answer based on python experience
Indeed, entities returned in a regular query result do not contain the entity key/ID. Attempting to obtain that from the entity is rather inefficient - you need to reach to the datastore for each individual entity (not even looking at why that doesn't appear to be working for you).
If I need the entity keys/IDs I'd instead use keys-only queries - obtaining the keys, from which I can easily get:
the key IDs, locally, without making actual datastore calls (in python via key.id(), I don't know the java equivalent)
the entities via direct key lookup, which can be batched for efficiency.
entity.getKey().getPathList().get(0).getId()
This help me to achieve the result. Getting entity Id through getKey method.

Querying on Collection attribute in Corda

I'm trying to search value inside Corda unconsumed states on a collection Field.
I'm able to search on String field using -
Field uniqueAttributeName = MySchema.PersistentIOU.class.getDeclaredField("fieldname");
CriteriaExpression uniqueAttributeEXpression = Builder.equal(uniqueAttributeName, "valueToSearch");
QueryCriteria customCriteria = new QueryCriteria.VaultCustomQueryCriteria(uniqueAttributeEXpression);
result = rpcOps.vaultQueryByCriteria(customCriteria, MyState.class).getStates();
Above worked fine when "fieldname" is String but I have another field which is List and I'm not sure how to search inside List for a specific value.
Please assist.
After a quick chat with #Roger3cev, we think the best way is to amend your ORM wrapper such that you have a parent - child relationship between the state and the list of fields you want to have in that list. Once you do this, you can use the JDBC connection available to you to query against the child state and then use the relationship to the parent to get the Corda state.

GQL query where field is not null

I have an entity kind called Account. One of the fields is a String named selfie, which is basically the url to a selfie uploaded by a user. I want to fetch for users who have a selfie (so if a user does not have a selfie they should not be included in the result set). I have the following query. but it won't work because I have "NULL" as a string. What is the correct way for doing this? Again, I only want users who have selfies.
Filter selfie = new FilterPredicate("selfie", FilterOperator.GREATER_THAN, "NULL");
Query query = new Query(Account.class.getSimpleName()).setFilter(selfie);
FetchOptions options = FetchOptions.Builder.withLimit(30);
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
QueryResultList<Entity> entities = datastore.prepare(query).asQueryResultList(options);
Also I am open to a JDO/JPA way of doing this on App-Engine (but it must work on App-Engine).
After some trial and error on https://console.cloud.google.com/datastore/entities/query/gql
I found this work around expression for IS NOT NULL:
> NULL
Example:
Select * from State where customer_id > NULL
I haven't tested this on a field with negative values.
This should be as simple as
Filter selfie = new FilterPredicate("selfie", FilterOperator.NOT_EQUAL, null);
where you actually pass the Java null value (not a String) and filter with not equals (see https://stackoverflow.com/a/22200137).
Personally, I've been using JDO for my datastore management, which has its pros and cons. Let me know if you'd like to see a solution using JDO as well. Cheers!

<Play!> Retrieving uniquely generated ID from <JPABase> in JPA

Folks,
I am using Play 1.2.5. The database is Oracle 10g and I am using an existing table for my application.
I am generating a unique key like this:
#GeneratedValue(strategy=GenerationType.SEQUENCE)
public int transactionId;
When I use the below code, the transactionId is generated and saved successfully ib the database:
transactionDetails.save();
But I am not able to get the uniquely generated transactionId once the save operation performs successfully. The save method returns a type <JPABase>. Then how can I retrieve the transactionId after a successful save operation from the <JPABase> ?
Note: I don't want to make another DB hit for fetching the transactionId because I believe that there might be some way to retrieve it for a successful save operation.
Please let me know about this.
Thanks,
You should be able to write
TransactionDetails savedDetails = transactionDetails.save();
save() method actually is not returning JPABase, it is declared as so you will get the saved entity

GAE Datastore querying by index

I have created entities in the datastore. I want to use the index assigned to them by the datstore for queries.
i.e get an iterable back where the id is greater than a given number
e.g.
Query q = new Query("MyEntity");
q.addFilter("id",Query.FilterOperator.GREATER_THAN_OR_EQUAL, startId);
PreparedQuery pq = datastore.prepare(q);
I know I can get back an individual entity back via id - but how to get a list ?
Cheers,
Iterable<Entity> myEntities = pq.asIterable();
List<Entity> myEntitiesInAList = pq.asList(FetchOptions.Builder.withChunkSize(500));
Side note:
"id" is not the name of the key assigned automatically by App Engine. I think you must use __key__ as the property name to do queries on it, and construct a full key as the search parameter, not just the long id.
If your intent is to remember where you left off and continue there on a subsequent query, consider using a query cursor. The example on that page might give you some further options.

Categories

Resources