Same EntityId in different contextElement in fiware - fiware

Is it possible to have 2 contextElements with the same entityId but different entityType in OrionCB?
Example:
In the same Orion CB these two elements:
1.entityId: 123456, entityType: device
2.entityId: 123456, entityType: conections
Would it be possible?

Yes, it is. A given entity is identified by the combination of both its ID and type.

Related

Changing attributes over time in relational database

At the core of my app is a table called Entities:
Entities:
-----------
id: number // PK
name: string
position_x: number
position_y: number
These entities have interactions with each other, called Events:
Events:
-----------
id: number // PK
name: string
date: Date
from: number // Entities FK
to: number // Entities FK
With events, we can manage all kinds of events between two entities. By selecting a timestamp / event, we can "time-travel" through each event, and see how changes affect the entities.
I just learned we want to support changes to entity attributes in the timeline as well. (travelling back should still get you the original attributes). So now I want to create a new Event-like table, which would look something like this:
SingleEntityEvents:
-----------
id: number // PK
name: string
date: Date
to: number // Entities FK
type: enum // CHANGE_NAME | CHANGE_POSITION
payload: json
Now my app would get the entities and render the original name if applicable, but render an updated name if there is a CHANGE_NAME event happening before the currently selected date. However, now I am leaning towards getting rid of the Entities table entirely, and make everything (including Entity creation) an event. But then how do I properly refer to these entities in the original (from -> to) Events? Is this even possible?
In other words, I want to be able to model this stream of events, but I am not sure how to:
Create entity through event:
name: 'Create Entity'
date: 01/01/2022
entityID: 123 // Its not to reference but to create an entity with this ID?
type: CREATE_ENTITY
payload: {
"name": "New Entity",
"position_x": 1,
"position_y": 0
}
If I select any time after this first event, the app should render an entity called "New Entity", positioned on coordinate (1, 0).
Update name of entity through event
name: 'Update Entity Name'
date: 01/03/2022
entityID: 123 // Now, since this is an update event, this is an actual reference to the previously created entity
type: UPDATE_ENTITY_NAME
payload: "Foo Bar"
If I select any time after this second event, the app should now render the same entity but it's now called "Foo Bar". Its position is unchanged so its still on (1, 0).
My question is, are there best practices to model such event streams? And how do I go about creating this entity ID?

How to differentiate the explicitly assigning null to the field or field that is not in the json file for #PATCH

I am using #PATCH for the partial update of the record.
My table is emp:
empId - Int
lastName -String
firstName - String
city - String
desc - String
Patch json file for emp/1:
{"city" : "NULL", "lastName": "newLastName"}
How can I pass this to the pl/sql procedure (how the sql query can be constructed only to update city and lastName) and how to differentiate between explicity city set to NULL and desc is not found in json.
There are multiple ways on how to deal with that kind of situation, I implemented at least two different ones:
Send a JSON document that represents the updated resource
Either you require the client to always send the complete JSON document (not a partial one) so you always get all values in a single request (easy). Absent values mean that the field is supposed to be null.
Or you allow the client to send a partial JSON document but then you need a unique identifier to distinguish between an absent field (not to touch) and a field that needs to be overridden with null (harder but not impossible).
Send a JSON document that contains operations on a resource, e. g. { "operation": "update", "field": "city", "value": "New City" } which replaces the old value of city with New City or { "operation": "delete", "field": "description" } which deletes description (requires parsing patches differently).

postgres store reference to field in json

It is possible to store json in postgres using the json data type. Check this tutorial for an introduction: http://www.postgresqltutorial.com/postgresql-json/
Consider I am storing the following json in such a field:
{
"address": {
"street1": "123 seasame st"
}
}
I want a to store separately a reference to the street field. For example, I might have another object which is using data from this json structure and wants to store a reference to where it got the data. Maybe something like this:
class Product():
__tablename__ = 'Address'
street_1 = Column(String)
data_source = ?
Now I could make data_source a string and just store namespaces like address.street, but if I did this postgres has no idea what that means. Working with that in queries would mean parsing the string and other inefficient stuff. Does postgres support referring to fields stored inside json data structures?
This question is related to JSON foreign keys in PostgreSQL , but in this case I don't necessarily want a fk relationship. I just want to create a reference, which is not necessarily enforced in the way a fk is.
update:
To be more clear, I want to reference the location of something in the json structure on another attribute and store that reference in a column. In the below code, Address.data_source is a reference to the location of the street data (for example address.street1 in this case)
class Address():
__tablename__ = 'Address'
street_1 = Column(String)
sample_id = Column(Integer, ForeignKey('DataSample.uid'))
data_source = ?
class DataSample():
__tablename__ = 'DataSample'
uid = Column(Integer, primary_key=True)
data = Column(JSONB)
body = {
"address": {
"street1": "123 seasame st"
}
}
datasample = DataSample(data=body)
address = Address(street_1=datasample.data['address']['street_1'],
sample_id=datasample.uid,
data_source=?)
As clarified, the question is seeking a way to flexibly specify a path within a JSON object of a particular record. Keys are being handled in normal columns. Constraints on JSONB fields are not available, and there is no specific support for specifying paths within JSON objects.
I worked with the following in SQL Fiddle using PostgreSQL 9.6:
CREATE TABLE datasample (
id integer PRIMARY KEY,
data jsonb
);
CREATE TABLE address (
id integer PRIMARY KEY,
street_1 text,
sample_id integer REFERENCES datasample (id),
data_source text
);
INSERT INTO datasample(id, data)
VALUES (1, '{"address":{"street_1": "123 seasame st"}}');
INSERT INTO address(id,street_1, sample_id, data_source)
VALUES (1,'123 seasame st',1,'datasample.data->''address''->>''street''');
A typical lookup of the street address (needed to retrieve street_1) would resemble:
SELECT datasample.data->'address'->>'street_1'
FROM datasample
WHERE id=1;
There is no special postgres type for identifying columns. Strings are the closest available and you will need to retrieve the string (or array of strings, or object containing strings, if one of those simplifies parsing) and use it to build the query. In tbe first code block, I stored it as the (escaped) fragment of query - 'datasample.data->''address''->>''street'''. Though longer, it would require only retrieval and unescaping to use in a new custom query. I did not find a way to use the string as a fragment within the same SQL statement, though it might be possible to combine it with other bits of text to form a full statement that could be run through EXECUTE.

Schema from nested JSON list

I have a JSON list which captures one to many relationships.
For example, School can have multiple Class objects and Class can have multiple Student objects, but Student only belongs to one Class and one School:
{
"School": [ {
"id": 1,
"name": "Grad School",
"Class": [ {
"name": 101,
"Student": [ {
"name": 501,
"propertyA": "test"
}]
}]
}]
}
I am trying to convert this JSON example into an appropriate schema but the nesting is causing issues. Apollo appears to be able to help but the example below isn't very descriptive:
https://launchpad.graphql.com/4nqqqmr19
I'm looking for suggestions on how to handle this situation, whether that be through a JSON schema converter (which handles nested situations) or other.
I think you issue is not really the schema, which to me looks straightforward:
You have these types (everything dummy code as you have not specified in what language/framework you want to provide the GraphQL-Api):
SchoolType
id ID
name String
classes [Class]
students [Students]
ClassType
id ID
name String
school School
students [Student]
StudentType
id ID
name String
class Class
school School
Then we need an entry point
classQueryType
name "school"
argument :id, ID
resolve do
schools.where(id: argument["id"])
So we have the schema. The bigger work is probably to get the different types to access the JSON Schema in a way that the types above work.
So let's say, we read the JSON data somehow, with the structure you have.
const DATA = JSON.parse("your-example.json")
We need to convert this into different collections of objects, so we can query them dynamically:
schools = []
classes = []
people = []
def build_schools(data)
data.schools.for_each do |school|
schools.push(
name: school.name,
id: school.id,
classes: build_classes(school)
)
end
end
def build_classes(school)
ids = []
school.classes.for_each do |class|
ids.push(class.id)
classes.push(
id: class.id
name: class.name
school_id: school.id # you create your own references, to associate these objects
students: build_students(class)
)
end
return ids
end
...
But then you still need to hook this up, with your type system. Which means to write your resolvers:
For example on the StudentType
StudentType
id ID
name String
class Class
school School
resolve(object) ->
school_id = students.where(id: object.id).class_id.school_id
schools.where(id: school_id)

MongoDB : Update Modifier semantics of "$unset"

In MongoDB, the update modifier unset works as follows:
Consider a Mongo DB Database db with a collection users. Users contain a Document, of the following format:
//Document for a user with username: joe
{
"_id" : ObjectId("4df5b9cf9f9a92b1584fff16"),
"relationships" : {
"enemies" : 2,
"friends" : 33,
"terminated" : "many"
},
"username" : "joe"
}
If I want to remove the terminated key, I have to specify the $unset update modifier as follows:
>db.users.update({"username":"joe"},{"$unset":{"relationships.terminated": "many"}});
My Question is, why do I have to specify the ENTIRE KEY VALUE PAIR for the $unset to work, instead of simply specifying:
>db.users.update({"username":"joe"},{"$unset":{"relationships.terminated"}});
Mon Jun 13 13:25:57 SyntaxError: missing : after property id (shell):1
Why not?
EDIT:
If the way to $unset is to specify the entire key value pair, in accordance with JSON specifications, or to add "1" as the value to the statement, why can't the Shell do the "1" substitution itself? Why isn't such a feature provided? Are there any pitfalls of providing such support?
The short answer is because {"relationships.terminated"} is not a valid json/bson object. A JSON object is composed of a key and a value, and {"relationships.terminated"} only has a key (or value, depends on how you look it).
Affortunately to unset a field in Mongo you do not need to set the actual value of the field you want to remove. You can use any value (1 is commonly used in Mongo docs) no matter the actual value of relationships.terminated:
db.users.update({"username":"joe"},{"$unset":{"relationships.terminated" : 1}});