I cant create data model for this database.
Firebase Realtime Database
I can't list chats with this model.
data class ChatModel( var voice : String ?= null,
var sender : String ?= null,
)
Example JSON
D/Log: DataSnapshot { key = J7AW1EgBx3cyP4eXfxYIBIfoT2J3, value =
{33447543={voice=https://firebasestorage.googleapis.com/v0/b/xxx.appspot.com/o/33447543.aac?alt=media&token=16e1f68b-2e2d-4c2b-976e-c30bdc38012d, chatwith=etcmobileapps, sender=mesut#gmail.com}, 32190281={voice=etcmobileapps.com, chatwith=etcmobileapps, sender=etcmobileap#gmail.com}} }
If I remove the chatwith value, chat messages appear on my screen, but not with chatwith.
I need data class model for chatwith and chats messages.
In your realtime database structure, you have sibling nodes with different structure. There is no straightforward way to convert that to a POJO/data class.
Probably the easiest solution is to restructure your realtime database and put all the chat messages under a new node. Something like this:
chats
|---J7AW1.....
|---messages
|---32190281
|---sender:
|---voice:
|---33447543
|---sender:
|---voice:
|---chatwith:
Then your ChatModel will be:
data class ChatModel(
val chatwith: String? = null,
val messages: List<ChatMessage>? = null
)
data class ChatMessage(
val sender: String? = null,
val voice: String? = null
)
Related
I have created the database name as bitnomy and saving the data to the collection name transactionModel, but when I hit the request it save to some collection name transactionmodels (which is nowhere link).
Can any one help me in this?
Given that you are using mongoose you can force the collection name during the Schema creation:
var UserInfo = new Schema({
username : String,
birthDate : Date
}, { collection: 'userinfo' });
This because by default mongoose pluralise the collection names, in this case would be users
I can't get Django to serialize the AL_NODE as a modelserializer. Is it possible to serialize AL_NODEs?
Here is my code:
class UserSecuritySelectionModelSerializers(serializers.ModelSerializer):
class Meta:
model = UserSecuritySelectionModel()
fields = ('hasChildNode', 'classificationNames', 'tgtWeight','currWeight','SSM','ext_model_id')
Here is a sample of the data and how it is structured in the database:
Code in my views.py
if request.is_ajax() and id is not None:
rootNode = UserSecuritySelectionModel.objects.get(SSM_id=id, classificationNameNode__isnull=True)
if not rootNode.is_root():
node = rootNode.get_root()
data = serializers.serialize('json', node, use_natural_foreign_keys=True)
return JsonResponse(data, safe=False)
userSelectionModelSerializer = UserSecuritySelectionModelSerializers(rootNode)
#data = serializers.serialize('json', [rootNode], use_natural_foreign_keys=True)
return JsonResponse (userSelectionModelSerializer.data, status=201, safe=False)
You say it's not working but you haven't included any details about the error you are getting. This makes everything here a guess.
You should just be setting the model reference to a class, not actually creating an instance of the model
model = UserSecuritySelectionModel()
# should be
class Meta:
model = UserSecuritySelectionModel
Next, I think you should explicitly pass in the instance just to be safe. It's not required, but it makes your intention clear:
UserSecuritySelectionModelSerializers(instance=rootNode)
Third, just return a standard Response, not a JsonResponse, DRF will do the content negotiation for you. That is why you are using it.
return Response(MyLongSerializer(instance=root).data)
Finally, is there any reason for sending a 201? You do not appear to be creating anything in the view. If you are, then send it like this:
return Response(..., status=HTTP_201_CREATED)
I'm working with Objectify to access DataStore in a Google App Engine application.
I have 2 Entities:
#Entity
public class Client {
#Id String id;
}
#Entity
public class Queue {
#Index #Id String name;
#Load LinkedHashMap<String,Ref<Client>> clientsInQueue;
}
In a transaction, i do something like this:
Client newClient = new Client(...);
ofy().save().entity(newClient);
Queue selectedQueue = ofy().load().type(Queue.class).id(queueName).now();
selectedQueue.getClientsInQueue().put(newClient.getId(), Ref.create(newClient));
But when i try to print all the elements in the LinkedHashMap, i noticed the elements is in the exactly reverse order.
For example if i add 2 Clients in the LinkedHashMap and save it, like this:
Queue selectedQueue = new LinkedHashMap<String,Ref<Client>>();
String id1 = "id1";
Client c1 = new Client(id1);
ofy().save().entity(c1);
String id2 = "id2"
Client c2 = new Client(id2);
ofy().save().entity(c2);
selectedQueue.getClientsInQueue().put(c1.getId(), Ref.create(c1));
selectedQueue.getClientsInQueue().put(c2.getId(), Ref.create(c2));
ofy().save().entity(selectedQueue);
Set<String> keys = selectedQueue.getClientsInQueue().keySet();
for(String key : keys){
Client c= selectedQueue.getClientsInQueue().get(key).get();
log.info("id: "+c.getId());
}
The result is:
id: id2
id: id1
Why i obtain this behavior ? I know that LinkedHashMap has to maintain the order of the keys! Is there any problem to use LinkedHashMap with GAE DataStore?
Thanks in advance.
Cheers,
Alessandro.
Fields of type Map<String, ?> are stored in the low level api as type EmbeddedEntity, the only map-like structure available as a property. This EmbeddedEntity is implemented as a non-linked HashMap. Consequently, there is no way for Objectify to preserve order.
I'll make a note of this in Objectify's documentation. If you would like this behavior to change, open up an issue in GAE's issue tracker requesting "Entity and EmbeddedEntity should use a LinkedHashMap to preserve order".
I'm currently developing a mobile application who uses a Google App Engine-hosted web service.
But i'm facing an issue. I just want to add a field in one my database's table.
App Engine doesn't use classic SQL syntax, but GQL. So i cannot use the ALTER TABLE statement. How can i do this with GQL ? I looked for a solution on the web, but there's not a lot of help.
public MyEntity() {
}
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Key idStation;
private String name;
private double longitude;
private double latitude;
private java.util.Date dateRefresh = new Date(); //the field i want to add in DB
So, now when i create a "MyEntity" object, it should add the "dateRefresh" field into the database... I create my object like this:
MyEntity station = new MyEntity();
station.setName("test");
station.setLatitude(0);
station.setLongitude(0);
station.setDateRefresh(new Date("01/01/1980"));
DaoFactory.getStationDao().addStation(station);
addStation method:
#Override
public MyEntity addStation(MyEntity station) {
EntityManager em = PersistenceManager.getEntityManagerFactory().createEntityManager();
try {
em.getTransaction().begin();
em.persist(station);
em.getTransaction().commit();
} finally {
if(em.getTransaction().isActive()) em.getTransaction().rollback();
em.close();
}
return station;
}
The field "dateRefresh" is never created into my DB...
Someone to help me please ?
Thanks in advance
Just add another field to your data structure, maybe providing a default clause, and that's all. For example, if you have a UserAccount:
class UserAccount(db.Model):
user = db.UserProperty()
user_id = db.StringProperty()
you may easily add:
class UserAccount(db.Model):
user = db.UserProperty()
user_id = db.StringProperty()
extra_info = db.IntegerProperty(default=0)
timezone = db.StringProperty(default="UTC")
and let it go.
While the datastore kinda mimics tables, data is stored on a per entity basis. There is no schema or table.
All you need to do is update your model class, and new entities will be saved with the structure (fields) of the new entity.
Old entities and indexes, however, are not automatically updated. They still have the same fields as they had when they were originally written to the datastore.
There's two ways to do this. One is to make sure your code can handle situations where your new properties are missing, ie make sure no exceptions are thrown, or handle the exceptions properly when you're missing the properties.
The second way is to write a little function (usu a mapreduce function) to update every entity with appropriate or null values for your new properties.
Note that indexes are not updated unless the entity is written. So if you add a new indexed property, old entities won't show up when you query for the new property. In this case, you must use the second method and update all the entities in the datastore so that they are indexed.
I'm trying to store JSON document into the AppEngine datastore using Objectify as persistence layer. To be able to query for document values, instead of just inserting the whole document as String field, I created a MapEntity which looks like this:
#Entity(name="Map")
public class MapEntity {
#Id
private Long id;
private Map<String,String> field;
// Code omitted
}
Since eventually when "unrolled" every key-value in the JSON document can be represented with Map
Example:
String subText = "{\"first\": 111, \"second\": [2, 2, 2], \"third\": 333}";
String jsonText = "{\"first\": 123, \"second\": [4, 5, 6], \"third\": 789, \"fourth\":"
+ subText + "}";
I will have the map fields stored in the datastore:
KEY VALUE
field.first => 123
field.second => [4,5,6]
field.third => 789
field.fourth-first => 111
field.fourth-second => [2,2,2]
field.fourth-third => 333
If I use my parse() method:
Parse the JSON document using JSON.Simple library and then do a recursive parse:
private MapEntity parse(String root, MapEntity entity, Map json) {
Iterator iter = json.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
if (entry.getValue() instanceof Map){
entity = parse((String)entry.getKey()+"-", entity, (Map) entry.getValue());
System.out.println("Map instance");
} else {
entity.setField(root + String.valueOf(entry.getKey()), String.valueOf(entry.getValue()));
}
}
return entity;
}
My app works like this:
MapEntity jsonEntity = new MapEntity();
Map json = null;
json = (Map) parser.parse(jsonText, containerFactory); // JSON.Simple parser
jsonEntity = parse("", jsonEntity, json);
Problems I encounter are:
I can't use the "." dot in the Map key field, so I have to use the "-"
Also my approach in storing JSON document is not very efficient
If your JSON follows a strict format, you'd probably be better off constructing a class to represent your data format and serializing directly to and from that class using a library like Jackson. You can use that class directly as your entity class in Objectify, but whether you want to do depends on whether you want to:
Store and expose the exact same set of data
Tightly couple your storage and JSON representations
You could use JSONObject as a replacement for your MapEntity and store the json to google app engine as a string using the toString() method. Upon retrieval you could simply restore the JSONObject using the appropriate constructor. This, of course, limits your ability to index properties in app engine and query against them.
If you want Objectify to do this for you, you could register a Translator to take care of calling the toString() and reconstruction.