neo4jphp relateTo() to a getResultSet() object - neo4jphp

I'm using the Neo4jphp REST API and I'm having a problem of relating a node iv created in my code to a node im retrieving from the neo4j database.
I'm retrieving the node as follows
$querystring="MATCH(n)"."WHERE has (n.name) and n.name='Interests'"."RETURN n";
$query=new Everyman\Neo4j\Cypher\Query($client,$querystring);
$result=$query->getResultSet();
im creating another node in my code using createNode()
$friend=$client->makeNode()->setProperty('name',$fname)->save();
I used relateTo() to relate them
$m=$client->getNode($result);
$m->relateTo($friend,$movi)->save();//$movi is a common movie name
but getting this error
PHP Catchable fatal error: Object of class Everyman\\Neo4j\\Query\\ResultSet could not be converted to string in /var/www/vendor/everyman/neo4jphp/lib/Everyman/Neo4j/Cache/EntityCache.php
would really appreciate any input

A neo4jphp query returns a row object (even if theres only one responce) so
$m=$client->getNode($result);
won't work
try this instead
$querystring="MATCH(n) WHERE has (n.name) and n.name='Interests' RETURN n";
$query=new Everyman\Neo4j\Cypher\Query($client,$querystring);
$result=$query->getResultSet();
foreach($result as $resultItem)
{
$resultArray[] = $resultItem['x'];
//$resultItem['x'] is the node object, now $result array is an array of node objects
}
$friend= $client->makeNode()->setProperty('name',$fname)->save();
$resultArray[0]->relateTo($friend,$movi)->save();
this code will also work with this query (easier to read)
$querystring="MATCH (n {name:"Interests"}) RETURN n";

I would do it this way:
$queryString = "MATCH(n) WHERE has (n.name) and n.name= {name} RETURN ID(n)";
$query = new Everyman\Neo4j\Cypher\Query($client,$queryString,array('name'=>'Interests'));
$result = $query->getResultSet();
$resultArray=array();
foreach($result as $row)
{
array_push($resultArray,$row['n']);
}
$friend = $client->getNode($resultArray[0]);
$friend->relateTo($friend,$movi)-save();

Related

'Parameter count mismatch' Error when trying to insert List<dynamic> to Excel using closedXml InsertData

I am trying to export dynamic list items to excel using ClosedXML. The goal is to allow end user to select the columns to be exported. Since the columns are dynamic, I use.ToDynamicListAsync() of System.Linq.Dynamic.Core name space.
The problem is excel export works fine if I create anonymous object but throws error when I directly pass the select query as shown below. I directly pass the select cols bcoz the cols will be known only at runtime.
Below is the code snapshot for clarity
using ClosedXML.Excel;
using System.Linq.Dynamic.Core;
var filter = "MeetingNo = 85";
var query = context.PrmProjects.AsNoTracking().Where(filter);
var items = await query.Select(x => new
{
x.OrganizationId,
x.ProjectNo,
x.MeetingNo,
x.Name
}).ToDynamicListAsync();
using var wb = new XLWorkbook();
var ws = wb.Worksheets.Add();
ws.Cell(3, 1).InsertData(items); /// WORKS FINE
var selectQuery = $"new(OrganizationId,ProjectNo,MeetingNo,Name)";
var items1 = await query.Select(selectQuery).ToDynamicListAsync();
using var wb2 = new XLWorkbook();
var ws2 = wb2.Worksheets.Add();
ws2.Cell(3, 1).InsertData(items1); /// THROW ERROR 'Parameter count mismatch'
`
In the above sample code InsertData with the list 'items' works fine but 'items1' throws an error 'Parameter count mismatch'
Screenshot of List 'items', working fine:
Screenshot of List 'items1', throw error:
Error screenshot:
Can any one please help me. What am I doing wrong.
The cause for this error is that System.Linq.Dynamic.Core creates a new dynamic type based on DynamicClass which does also have an indexer:
public object? this[string name]
{
get
{
//
}
set
{
//
}
}
The ClosedXml calls GetProperties(...) in the ObjectReader.cs class and this GetProperties does return 5 entries:
OrganizationId
ProjectNo
MeetingNo
Name
Index --> This is the indexer defined on the DynamicClass which is not really a normal property.
So actually ClosedXML should be fixed to exclude indexer methods.
Example:
int parameters = propertyInfo.GetIndexParameters().Length;
if (parameters > 0)
{
// The property is an indexer, skip this.
continue;
}

How to test for Empty array value in Unirest json Response

I have the following code snipet used in Jira Script Runner cloud
String _userId
def result = get(graph_base_user_url + "?")
.header("Authorization","Bearer " + AuthToken )
.queryString("\$filter","mail eq '$userEmail'")
.asJson()
if (result.getStatus().toString() =="200")
{
**if (result.getBody().value){ // <<<<< is Value is not empty ???
_userId=result.getBody().value[0].id
}**
else
_userId="-1" // user does not exist
}
// user ID not found : error 404
if (result.getStatus().toString()=="404")
_userId="User not found"
This code is returning in the result.getBody() the following output
{"#odata.context":"https://graph.microsoft.com/v1.0/$metadata#users","value":[]}
What I am trying to achieve is to test if the value array of the response is empty or not and if not empty I need to fetch the first element item as value[0].Id, but I could not get it correctly
How can I define my code in BOLD above to perform my correct test ?
Error I get from my code is : " Value is not a property of JsonNode object
Thanks for help
regards
from official doc http://kong.github.io/unirest-java/#responses
String result = Unirest.get("http://some.json.com")
.asJson()
.getBody()
.getObject()
.getJSONObject("car")
.getJSONArray("wheels")
.get(0)
so, something like this should work for you:
def a = result.getBody().getObject().getJSONArray("value")
if(a.length()>0) _userId = a.get(0).get("id")

How can i simplify checking if a value exist in Json doc

Here is my scenario, i am parsing via javascript a webpage and then post the result to an restApi to store the json in a db. The code works fine as long as all fields i defined in my script are send. Problem is over time they website might change names for fields and that would cause my code to crash.
Originally i used code like this
const mySchool = new mls.School();
mySchool.highSchoolDistrict = data["HIGH SCHOOL DISTRICT"].trim();
mySchool.elementary = data.ELEMENTARY.trim();
mySchool.elementaryOther = data["ELEMENTARY OTHER"].trim();
mySchool.middleJrHigh = data["MIDDLE/JR HIGH"].trim();
mySchool.middleJrHighOther = data["MIDDLE/JR HIGH OTHER"].trim();
mySchool.highSchool = data["HIGH SCHOOL"].trim();
mySchool.highSchoolOther = data["HIGH SCHOOL OTHER"].trim();
newListing.school = mySchool;
but when the element does not exist it complains about that it can not use trim of undefined. So to fix this i came up with this
if (data["PATIO/PORCH"]) {
newExterior.patioPorch = data["PATIO/PORCH"].trim();
}
this works but i am wondering if there is a more global approach then to go and check each field if it is defined ?
You could leverage a sort of helper function to check first if the item is undefined, and if not, return a trim()-ed version of the string.
var data = Array();
data["HIGH SCHOOL DISTRICT"] = " 123 ";
function trimString(inputStr) {
return (inputStr != undefined && typeof inputStr == "string") ? inputStr.trim() : undefined;
}
console.log(trimString(data["HIGH SCHOOL DISTRICT"]));
console.log(trimString(data["ELEMENTARY OTHER"]));

Getting node by id and parameters with Neo4j-Driver for nodejs

I'm trying to return a specific node with the id (using neo4j-driver package within my nodejs server). I have the id of the node I'm searching for. So I used the parameters in the run method as showed bellow but I'm not getting any nodes.
session.run('MATCH (n:User)-[:OWN]->(a) WHERE id(n) = $id RETURN a',{id: idUser})
I checked and idUser-value is 128 and when i'm running this command, I get the right node.
session.run('MATCH (n:User)-[:OWN]->(a) WHERE id(n) = 128 RETURN a',{id: idUser})
Is there any one to make the first command working so I can get the node of the given id ?
Thanks
As it is written in the driver documentation:
Number written directly e.g. session.run("CREATE (n:Node {age:
{age}})", {age: 22}) will be of type Float in Neo4j. To write the age
as an integer the neo4j.int method should be used...
https://github.com/neo4j/neo4j-javascript-driver#write-integers
So when you pass the identifier from the node.js, you need to convert it:
session
.run('MATCH (n:User)-[:OWN]->(a) WHERE id(n) = $id RETURN a', {
id: neo4j.int(idUser)
})
or:
session
.run('MATCH (n:User)-[:OWN]->(a) WHERE id(n) = toInteger($id) RETURN a', {
id: idUser
})

Linq Invalid Cast Exception Same Object Type

I wrote this query and as my understanding of the business rules has improved I have modified it.
In this most recent iteration I was testing to see if indeed I had some redundancy that could be removed. Let me first give you the query then the error.
public List<ExternalForums> GetAllExternalForums(int extforumBoardId)
{
List<ExternalForums> xtrnlfrm = new List<ExternalForums>();
var query = _forumExternalBoardsRepository.Table
.Where(id => id.Id == extforumBoardId)
.Select(ExtForum => ExtForum.ExternalForums);
foreach (ExternalForums item in query)
{
xtrnlfrm.Add(new ExternalForums { Id = item.Id , ForumName = item.ForumName, ForumUrl = item.ForumUrl });
}
return xtrnlfrm;
}
Now in case it isn't obvious the query select is returning List of ExternalForums. I then loop through said list and add the items to another List of ExternalForums object. This is the redundancy I was expecting to remove.
Precompiler was gtg so I ran through it one time to very everything was kosher before refactoring and ran into a strange error as I began the loop.
Unable to cast object of System.Collections.Generic.HashSet
NamSpcA.NamSpcB.ExternalForums to type NamSpcA.NamSpcB.ExternalForums.
Huh? They are the same object types.
So am I doing something wrong in the way I am projecting my select?
TIA
var query = _forumExternalBoardsRepository.Table
.Where(id => id.Id == extforumBoardId)
.Select(ExtForum => ExtForum.ExternalForums);
This query returns IEnumerable<T> where T is type of ExtForum.ExternalForums property, which I would expect to be another collection, this time of ExternalForum. And the error message matches that, saying you have IEnumerable<HashSet<ExternalForums>>.
If you need that collection of collections to be flattened into one big collection of ExternalForums use SelectMany instead:
var query = _forumExternalBoardsRepository.Table
.Where(id => id.Id == extforumBoardId)
.SelectMany(ExtForum => ExtForum.ExternalForums);

Resources