send a query in neo4j [JAVA] - java

I am new to neo4j and graph database, and I have to send a query to get some values.
I have food and category nodes, and the relationship type between the two is specified by another node categorized_as.
What I need to fetch is the pair of food_name and its category_name.
Thanks for your help in advance.

Here's the documentation on how to run cypher queries from java. Adapted for your example, it would look like this:
// Create a new graph DB at path DB_PATH
GraphDatabaseService db = new GraphDatabaseFactory().newEmbeddedDatabase( DB_PATH );
// Create a new execution engine for running queries.
ExecutionEngine engine = new ExecutionEngine( db );
ExecutionResult result;
// Queries need to be run inside of transactions...
try ( Transaction ignored = db.beginTx() )
{
String query = "MATCH (f:food)-[:categorized_as]->(c:category) RETURN f.food_name as foodName, c.category_name as categoryName";
// Run that query we just defined.
result = engine.execute(query);
// Pull out the "foodNames" column from the result indicated by the query.
Iterator<String> foodNames = result.columnAs( "foodName" );
// Iterate through foodNames...
}

Related

Mongo Db Query to sort by the field and also aggregate the results which do not have that field

query should be sorted by 'lastUsedTimestamp' in ASC. If these entities lastUsedTimestamp is null or expired or do not have the field, we just remove them from the collection with defined limit.
I have them written like below but it is giving null
Criteria fieldsCriteria1 = Criteria.where("lastAccessTimestamp").lte(date);
Criteria fieldsCriteria2 = Criteria.where("lastAccessTimestamp").exists(false);
Query query2 = new Query();
query2.limit(3);
query2.with(Sort.by(Sort.Direction.ASC,"lastAccessTimestamp")); // to set in ASC order
query2.addCriteria(fieldsCriteria1); // to set the expired time
If i have only these above criteria added it works fine, the problem occurs when i add the below criteria
query2.addCriteria(fieldsCriteria2); // to get if the lastAccessTimestamp field is empty
I am new to Mongo Db, also I am not sure which is the best way to fulfill the above query.
I had figured out the solution, the below query worked for me.
var fieldsCriteria = new Criteria()
.orOperator(Criteria.where(LAST_ACCESS_TIMESTAMP).lt(date)
,Criteria.where(LAST_ACCESS_TIMESTAMP).exists(false)
);
var query = new Query();
query.limit(limit);
query.with(Sort.by(Sort.Direction.ASC, LAST_ACCESS_TIMESTAMP));
query.addCriteria(fieldsCriteria);
List<Document> list=mongoTemplate.find(query,Document.class,collectionName);

Reuse an stream in esper in several queries

I'm trying to use EsperIO to load some information from database and use it in other queries with different conditions. To do it I'm using the following code:
ConfigurationDBRef dbConfig = new ConfigurationDBRef();
dbConfig.setDriverManagerConnection("org.postgresql.Driver",
"jdbc:postgresql://localhost:5432/myDatabase",
"myUser", "myPassword");
Configuration engineConfig = new Configuration();
engineConfig.addDatabaseReference("myDatabase", dbConfig);
// Custom class
engineConfig.addEventType("UserFromDB", UserDB.class);
EPServiceProvider esperEngine = EPServiceProviderManager.getDefaultProvider(engineConfig);
String statement = "insert into UserFromDB "
+ " select * from sql:myDatabase ['SELECT * from data.user']";
//Install this query in the engine
EPStatement queryEngineObject = esperEngine.getEPAdministrator().createEPL(statement);
// 1. At this point I can iterate over queryEngineObject without problems getting the information sent by database
// This query is only a 'dummy example', the 'final queries' are more complex
statement = "select * from UserFromDB";
EPStatement queryEngineObject2 = esperEngine.getEPAdministrator().createEPL(statement);
// 2. If I try to iterate over queryEngineObject2 I receive no data
How can I reuse UserFromDB stored information in other queries? (in the above example, in queryEngineObject2)
You don't have a stream since the database doesn't provide a stream. The database query provides rows only when its being iterated/pulled.
One option is to loop over each row and send it into the engine using "sendEvent":
// create other EPL statements before iterating
Iterator<EventBean> it = statement.iterator();
while(it.hasNext()) {
epService.getEPRuntime().sendEvent(event);
}

BigQuery Java client - how to query external ( federated ) table?

I am using the new google-cloud-bigquery and google-cloud-storage api. I want to query an external table, which I created like this:
ExternalTableDefinition etd = ExternalTableDefinition.newBuilder(bucketPath, schema, FormatOptions.csv()).build();
TableId tableID = TableId.of(dataset, targetTableName);
TableInfo tableInfo = TableInfo.newBuilder(tableID, etd).build();
Now I want to query this table, but to have it as a temporary one, using the QueryRequest:
QueryRequest queryRequest = QueryRequest.newBuilder("select * from table limit 10 ").setUseLegacySql(true).setDefaultDataset(dataset).build();
QueryResponse response = client.query(queryRequest);
But it fails due to a table not exists, which makes sense. I am trying to do something similar to this command line:
bq query --project_id=<project ID> --external_table_definition=wikipedia::/tmp/wikipedia 'select name from wikipedia where name contains "Alex";'
but in Java.
To summarize: how do I create and query an external temporary table through Java client for big query?
Reference from documentation:
https://cloud.google.com/bigquery/external-data-sources#temporary-tables
For reference, here is the way to do it:
public static void main(String[] args)
{
BigQuery bigquery =
BigQueryOptions.getDefaultInstance().getService();
ExternalTableDefinition etd =
ExternalTableDefinition.newBuilder("gs://", createSchema(),
FormatOptions.csv()).build();
TableId tableId = TableId.of("testdataset", "mytablename");
bigquery.create(TableInfo.newBuilder(tableId, etd).build());
//Now query the table project.testdataset.mytablename
}

How to concurrently read and update a field of mongodb from java

Let's take an example of facebook posts where multiple users give likes to a post. Now for some post currently database stores 10 likes and if two users liked that post concurrently then both will read 10 as current like and update 11 one by one but the correct value should be 12. How to achieve this using mongodb and java.
Check the operator $inc.
Here is a sample code from this link:
// connect to MongoDB server.
Mongo mongo = new Mongo("localhost", 27017);
DB database = mongo.getDB("mydb");
DBCollection collection = database.getCollection("testCollection");
// create a simple db object where counter value is 0
DBObject temp = new BasicDBObject("name", "someName").append("counter", 0);
// insert it into the collection
collection.insert(temp);
// create an increment query
DBObject modifier = new BasicDBObject("counter", 1);
DBObject incQuery = new BasicDBObject("$inc", modifier);
// create a search query
DBObject searchQuery = new BasicDBObject("name", "someName");
// increment a counter value atomically
WriteResult upRes = collection.update(searchQuery, incQuery);

Convert mysql join query to morphia mongodb

Currently, we've our application on Play 1.2.5 with MySQL on the backend. We're trying to port this system to MongoDB using Morphia.
We're having problem while converting the MySQL Join Queries to MongoDB that uses Morphia. Following is the SQL query:
SELECT jobs.postal, count(distinct timesegments_id), group_concat(timesegments_id order by timesegments_id) as types, latitude, longitude FROM jobs
left join geocodes on jobs.geocode_id = geocodes.id left join jobs_timesegments on jobs_timesegments.jobs_id = jobs.id
where geocodes.last_updated is not null
and longitude >0
and timesegments_id is not null
group by jobs.postal;
Following is what we tried:
List<models.Geocode> Geocodelist = models.Geocode.find().filter("longitude >",0).filter("last_updated",new BasicDBObject("$ne","last_updated")).asList();
List<String> geocodeids = new ArrayList<String>();
for (models.Geocode geocode : Geocodelist) {
geocodeids.add(geocode.getIdAsStr());
}
List<models.Job> job = models.Job.find().filter("geocode_id",new BasicDBObject("$in",geocodeids)).asList();
List<String> jobids = new ArrayList<String>();
for (models.Job joblist : job) {
jobids.add(joblist.getIdAsStr());
}
List<models.Jobs_TimeSegments> timesegments_data = models.Jobs_TimeSegments.find().filter("jobs_id",new BasicDBObject("$in",jobids)).asList();
The above fetches three lists; however, we're not sure how to reference them to each other and get the list of columns that we want.
Any help is highly appreciated.
Thanks

Categories

Resources