How can I import data into Memgraph from local JSON file? - memgraphdb

I have data that I want to import into the database in JSON format. I want to import parts of that data as graph objects: nodes or relationships. My JSON file looks like this:
{
"first_name": "Jessica",
"last_name": "Rabbit",
"pets": ["dog", "cat", "bird"]
}
How can I do that?

To create a node with the label Person and first_name, last_name and pets as properties, run the following Cypher query:
CALL json_util.load_from_path("path/to/data.json")
YIELD objects
UNWIND objects AS o
CREATE (:Person {first_name: o.first_name, last_name: o.last_name, pets: o.pets});

Related

How to get a field on string data in Ruby for Redis?

I have a dataset with the name of table1 in Redis like below:
[
{
"column-name1": "10.1.10.1",
"column-name2": "range(100,200)",
"column-name3": "nam3"
},
{
"column-name1": "2.2.2.2",
"column-name2": "",
"column-name3": "range(1024,+inf)"
},
{
"column-name1": "1.1.1.1",
"column-name2": "",
"column-name3": "nam3"
}
]
I want to get values of table1.. How can I do it?
How can I parse table1 in ruby to reach its values?
Frist, you should parse json data from stored string in Redis. For parsing json in Ruby you can do something like below:
require "redis"
require "json"
red = Redis.new(host: "127.0.0.1", port: 6379, db: 1) <-- connect to redis
table1 = red.get("table1") <-- get table1 value (stringified data)
table1_json = JSON.parse(table1) <-- parse value to get a JSON object
now you have your table1 data as a json object and you can iterate over its elements and get the values you want:
for key in table1_json
puts(key["column-name1"])
end

Sort GraphQL query results in the exact order of input array

I need to get a number of items from a GraphQL enabled database (no control over its schema) and output them in the exact order called.
For example, if the database holds the items 1,2,3 in that respective order I need to get them as 3,1,2.
Query:
{items(filter: {id: {_in: ["3","1","2"] } } ) {data}}
Actual result:
{"data": {"items": [{"data": "data-from-1"},{"data": "data-from-2"},{"data": "data-from-3"}]}}
Expected result:
{"data": {"items": [{"data": "data-from-3"},{"data": "data-from-1"},{"data": "data-from-1"}]}}
So I guess that what I'm looking for is a 'meta' operator that relates to other operators rather than the actual query – something like:
sort:["_in"] or orderby:{operator:"_in"}
...but I didn't manage to find out if such a thing exists or not.
So is it possible in general or maybe in some flavour of GraphQL? Or is it my only choice to prebuild a query with aliases and do it like this:
{
_3: items(filter:{id: { _eq: "3" }}){data}
_1: items(filter:{id: { _eq: "1" }}){data}
_2: items(filter:{id: { _eq: "2" }}){data}
}
Which GraphQL client are you using?
If you're using Apollo, and you really don't have access to the schema/resolvers in the server, you can create a local field and resolve it on your own, and so you can manipulate as much as you want.
Reference
https://www.apollographql.com/docs/react/local-state/managing-state-with-field-policies/#defining
Basically, if you're querying a field like:
query {
someQuery(someFilter: {foo: "bar"}) {
items {
data
}
}
}
You can create a local field and write a typePolicy to it. Then you can query something like:
query {
someQuery(someFilter: {foo: "bar"}) {
items {
data
}
parsedItems #client
}
}
Then you can get data from ìtems and resolve parsedItems locally as you want.

Marshmallow deserialization [(obj, "str"), (obj, "str"), (obj, "str"), ...]

I'm working with an existing mssql database, where I'm not able to make any changes. Trying to make an API using Flask and Marshmallow. I have some issues deserializing the following query returning all people working on a project.
query = (
sa.session.query(Employee, sa.func.sum(JobEntry.number_registered).label("total"))
.join(JobEntry, Employee.employee_hashkey==JobEntry.employee_hashkey)
.filter(JobEntry.project_number==f'{project_number}')
.group_by(Employee)
).limit(3).all()
The query returns
print(query)
[(<Employee 188ED6A858997A48FDA53A404779A16F>, 229.0), (<Employee 1D40AB9C2A973C2BD33B1EF6108D2A70>, 2.0), (<Employee 38584E42E883131DC35151E4922A8094>, 176.75)]
The Employee contains the name, id, etc. How would I create a marshmallow schema returning, the following example.
[
{"name": "somename a", "total" 229.0, "id": 11},
{"name": "somename b", "total" 2.0, "id": 22},
{"name": "somename c", "total" 176.75, "id": 33}
]
Being a noob, I have experimented a bit... The following code returns almost what I want. But I get "Employee." in my keys ...
class ProjectUsersSchema(Schema):
class Meta:
model = Employee
fields = (
"Employee.name",
"Employee.id"
"total"
)
# returns "[{"Employee.name": "somename a", "total" 229.0, "Employee.id": 11}, ..."
Made a temporary f#ckly fix using nested schemas by including .split(".")[-1] into my snake_case to PascalCase schema
def pascalcase(s):
part_lst = s.split(".")[-1].split("_") # todo fix split(".")[-1]
if len(s) <= 2:
return "".join(i.upper() for i in part_lst)
else:
return "".join(i.title() for i in part_lst)
class PascalCaseSchema(ma.SQLAlchemyAutoSchema):
def on_bind_field(self, field_name, field_obj):
field_obj.data_key = pascalcase(field_obj.data_key or field_name)`

How can i separate a column from a Map in deluge?

I am using Zoho deluge to write a function. I actually call an API and I get the following response:
[
{"name": "abc", email: "abc#xyz.com" },
{"name": "qwc", email: "qwc#mnh.com" }
]
I have converted it into the JSONArray (Map). However, I do not want to run a loop to get email values because there are 10k entries.
Could anyone please help me to extract the email column from the response?
Only way i know(for deluge) is to use a loop. Unfortunately Zoho interrupts a Function after 40 loops(Guess it was 40). Do you have any option to give the API parameters to filter for the values you need?(In Zoho it is possible)
Extracting the email column can probably be done using Deluge's executeXpath() function which seems to work on Deluge-Maps, and Json as well as XML data.
Here is an example:
//----------------------------------------------------------------
// Recreate the example data structure from the question.
//----------------------------------------------------------------
response = list(
{"name": "abc", email: "abc#xyz.com" },
{"name": "qwc", email: "qwc#mnh.com" }
);
my_data = {"my_list": response};
//----------------------------------------------------------------
// Extract raw email data that will include field separator: "-|-"
//----------------------------------------------------------------
raw_email_data = my_data.executeXpath("/root/my_list/email/text()");
//----------------------------------------------------------------
// Remove the field separator: "-|-"
// This should result in a list: "abc#xyz.com", "qwc#mnh.com",...
//----------------------------------------------------------------
email_list = raw_email_data.toList("-|-");

Enforce that a Grape Entity always returns an array?

How can I enforce that my Grape Entity always returns an array (collection) even if its just a singular object? I have heard that some people create a helper method that gets called inside their endpoint, but I have not found any examples of anyone doing that, online.
The default functionality of an Entity is that it returns an object if only a single document (mongoid object) is returned. If a collection of documents is returned then it returns an array, I dont want my client application having to do a check every time to see if an object or an array got returned from my API.
## Resource (HTTP Endpoint)
desc 'List departments a user can and cannot access'
params do
requires :user_id
end
get :department_access do
#user = BACKBONE::User.find(#access_key.user_id)
requires_admin!
user = BACKBONE::User.find(params[:user_id])
can_access = BACKBONE::Department.user_can_access(user)
no_access = BACKBONE::Department.user_cannot_access(user)
present_success can_access
present :can_access, can_access, with: BACKBONE::Entities::DepartmentBase
present :no_access, no_access, with: BACKBONE::Entities::DepartmentBase
end
-
## Entity
module BACKBONE
module Entities
class DepartmentBase < BACKBONE::Entities::Mongoid
expose :name
expose :prefix
with_options(format_with: :mongo_id) do
expose :company_id
end
end
end
end
JSON Response
{
"status": "success",
"request_time": 0.009812,
"records": 1,
"can_access": {
"id": "59699d1a78cee4f8d07528fc",
"created_at": "2017-07-14T21:42:02.666-07:00",
"updated_at": "2017-07-14T21:42:02.666-07:00",
"name": "Tenant Improvement",
"prefix": "CACC",
"company_id": "596927fb670f6eec21c4f409"
},
"no_access": {
"id": "59699cca78cee4f8d07528fb",
"created_at": "2017-07-14T21:40:42.005-07:00",
"updated_at": "2017-07-14T21:40:42.005-07:00",
"name": "Field Operations",
"prefix": "CACC",
"company_id": "596927fb670f6eec21c4f409"
}
}
a coworker and I came up with a solution with a helper, create a helper method that always returns an array:
def present_array(key, data, entity)
d = (data.class.respond_to? :count) ? [data] : data
d = [] if d.nil?
present key, d, entity
end

Resources