py2neo v4 create a relationship with 2 existing node in database - python-3.x

i have this problem
With py2neo how can I create a relationship between 2 existing nodes in my database select them using the id.
In the py2neo documentation I find only examples that create the nodes at the moment and associate them directly with merge
I try this in my code:
db = conn()
data = DataFrame(db.run("MATCH (n:personalesanitario) RETURN ID(n) LIMIT 100").data())
x = 0
WORKIN = Relationship.type("WORKIN")
while (x <= 99):
#print(data['ID(n)'][x])
n1 = db.evaluate("MATCH (n:personalesanitario) WHERE ID(n) = $id RETURN 1",parameters = {'id':int(data['ID(n)'][x])})
print(n1)
n2 = db.evaluate("MATCH (n:reparti) WHERE ID(n) = $id RETURN 1",parameters = {'id':randint(101,109)})
#print(n2)
db.merge(WORKIN(n1,n2))
x = x+1

Change return 1 to Return n in those two queries.
It's not returning node but string.

Related

Selecting random rows from table with sqlalchemy gives not random results

I have, on a pgsql backend, a table and an (allegedly) random access version of it:
class Topic(db.Model):
id = db.Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
question_id = db.Column(UUID(as_uuid=True), db.ForeignKey("question.id"))
topic = db.Column(Enum(QuestionTopicsChoices))
# Create an alias for Topic that uses BERNOULLI sampling method
Topic_rnd = db.aliased(Topic, tablesample(Topic, func.bernoulli(2.5), 10))
I'd expect, then, that these two queries return with different results:
topics_linear = Topic.query.filter_by(topic='emotion').all()
topics_random = Topic_rnd.query.filter_by(topic='emotion').all()
but they return the records in the same order. What am I doing wrong?

Couchbase - Case with subquery

I am going to write a case which has subquery, something like below, But I cannot get neither out put nor error:
select
case
when f.resGeo.isRural = true
then (select g.ID as geo_id
from bktsample.scpPC.GeoInfo g
where g.PROVINCE_ID = f.resGeo.province.id
and g.CITYES_ID = f.resGeo.countie.id
and g.PART_ID = f.resGeo.part.id
and g.CITYORCOUNTRY_ID = f.resGeo.countie.id
and g.VILLAGE_ID = f.resGeo.village.id)
when f.resGeo.isRural = false
then (select g.ID
from bktsample.scpPC.GeoInfo g
where g.PROVINCE_ID = f.resGeo.province.id
and g.CITYES_ID = f.resGeo.countie.id
and g.PART_ID = f.resGeo.part.id
and g.CITYORCOUNTRY_ID = f.resGeo.countie.id)
end as geo_id
from bktsample.scpPC.Family f;
PS: GEO is my collection, scpPC is my scope and bktsample is my bucket.
Each document in the Family collection should have returned one document of geo_id (either empty array or objects of ID)
Small change to your query:
CREATE INDEX ix1 ON bktsample.scpPC.Family(resGeo.province.id, resGeo.countie.id, resGeo.part.id, resGeo.countie.id, resGeo.village.id, resGeo.isRural);
CREATE INDEX ix2 ON bktsample.scpPC.GeoInfo(PROVINCE_ID, CITYES_ID, PART_ID, CITYORCOUNTRY_ID, VILLAGE_ID, ID);
SELECT
(SELECT g.ID AS geo_id
FROM bktsample.scpPC.GeoInfo AS g
WHERE g.PROVINCE_ID = f.resGeo.province.id
AND g.CITYES_ID = f.resGeo.countie.id
AND g.PART_ID = f.resGeo.part.id
AND g.CITYORCOUNTRY_ID = f.resGeo.countie.id
AND (f.resGeo.isRural == false OR g.VILLAGE_ID = f.resGeo.village.id))
) AS geo_ids
FROM bktsample.scpPC.Family f
WHERE f.resGeo.province.id IS NOT NULL;

Error while getting user input and using Pandas DataFrame to extract data from LEFT JOIN

I am trying to create Sqlite3 statement in Python 3 to collect data from two tables called FreightCargo & Train where a train ID is the input value. I want to use Pandas since its easy to read the tables.
I have created the code below which is working perfectly fine, but its static and looks for only one given line in the statement.
import pandas as pd
SQL = '''SELECT F.Cargo_ID, F.Name, F.Weight, T.Train_ID, T.Assembly_date
FROM FreightCargo F LEFT JOIN [Train] T
ON F.Cargo_ID = T.Cargo_ID
WHERE Train_ID = 2;'''
cursor = conn.cursor()
cursor.execute( SQL )
names = [x[0] for x in cursor.description]
rows = cursor.fetchall()
Temp = pd.DataFrame( rows, columns=names)
Temp'''
I want to be able to create a variable with an input. The outcome of this action will then be determined with what has been given from the user. For example the user is asked for a train_id which is a primary key in a table and the relations with the train will be listed.
I expanded the code, but I am getting an error: ValueError: operation parameter must be str
Train_ID = input('Train ID')
SQL = '''SELECT F.Cargo_ID, F.Name, F.Weight, T.Train_ID, T.Assembly_date
FROM FreightCargo F LEFT JOIN [Train] T
ON F.Cargo_ID = T.Cargo_ID
WHERE Train_ID = ?;''', (Train_ID)
cursor = conn.cursor()
cursor.execute( SQL )
names = [x[0] for x in cursor.description]
rows = cursor.fetchall()
Temp = pd.DataFrame( rows, columns=names)
Temp
The problem lays in your definition of the SQL variable.
You are creating a tuple/collection of two elements. If you print type(SQL) you will see something like this: ('''SELECT...?;''', ('your_user's_input')).
When you pass this to cursor.execute(sql[, parameters]), it is expecting a string as the first argument, with the "optional" parameters. Your parameters are not really optional, since they are defined by your SQL-query's [Train]. Parameters must be a collection, for example a tuple.
You can unwrap your SQL statement with cursor.execute(*SQL), which will pass each element of your SQL list as a different argument, or you can move the parameters to the execute function.
Train_ID = input('Train ID')
SQL = '''SELECT F.Cargo_ID, F.Name, F.Weight, T.Train_ID, T.Assembly_date
FROM FreightCargo F LEFT JOIN [Train] T
ON F.Cargo_ID = T.Cargo_ID
WHERE Train_ID = ?;'''
cursor = conn.cursor()
cursor.execute( SQL, (Train_ID,) )
names = [x[0] for x in cursor.description]
rows = cursor.fetchall()
Temp = pd.DataFrame( rows, columns=names)
Temp

AutoQuery/OrmLite incorrect total value when using joins

I have this autoquery implementation
var q = AutoQuery.CreateQuery(request, base.Request).SelectDistinct();
var results = Db.Select<ProductDto>(q);
return new QueryResponse<ProductDto>
{
Offset = q.Offset.GetValueOrDefault(0),
Total = (int)Db.Count(q),
Results = results
};
The request has some joins:
public class ProductSearchRequest : QueryDb<GardnerRecord, ProductDto>
, ILeftJoin<GardnerRecord, RecordToBicCode>, ILeftJoin<RecordToBicCode, GardnerBicCode>
{
}
The records gets returned correctly but the total is wrong. I can see 40,000 records in database but it tells me there is 90,000. There is multiple RecordToBicCode for each GardnerRecord so it's giving me the number of records multiplied by the number of RecordToBicCode.
How do I match the total to the number of GardnerRecord matching the query?
I am using PostgreSQL so need the count statement to be like
select count(distinct r.id) from gardner_record r etc...
Dores OrmLite have a way to do this?
I tried:
var q2 = q;
q2.SelectExpression = "select count(distinct \"gardner_record\".\"id\")";
q2.OrderByExpression = null;
var count = Db.Select<int>(q2);
But I get object reference not set error.
AutoQuery is returning the correct total count for your query of which has left joins so will naturally return more results then the original source table.
You can perform a Distinct count with:
Total = Db.Scalar<long>(q.Select(x => Sql.CountDistinct(x.Id));

what is the easiest way to check for the equality of two db rows using groovy sql

Is there a simple and concise way to check that two rows of a given Table contains the same data in all columns?
I haven't tested this, but it seems the most obvious solution:
// get an Sql instance
def db = [url:'jdbc:hsqldb:mem:testDB', user:'sa', password:'',
driver:'org.hsqldb.jdbcDriver']
def sql = Sql.newInstance(db.url, db.user, db.password, db.driver)
// Get 2 rows
GroovyRowResults row1 = sql.firstRow("select * from user where id = 4")
GroovyRowResults row2 = sql.firstRow("select * from user where email = 'me#example.org'")
// compare them
boolean identical = row1.equals(row2)
Not especally Groovy, but I'd make SQL do the lifting a la something like:
db.firstRow("SELECT COUNT(DISTINCT CONCAT(city,state,zip)) FROM Candidates WHERE id IN (1,2)")[0] == 0

Resources