Execution engine not printing results - java

I have a simple Query method that runs cypher queries as noted below. If I run the EXACT same query in the web console (yes, same db instance, correct path), I get a non-empty iterator in the console. Shouldn't I 1) not get that message and 2) get the results I see in my database?
This class has other methods that add data to the database and that functionality works well. This query method is not working...
Class:
import org.neo4j.cypher.javacompat.ExecutionEngine;
import org.neo4j.cypher.javacompat.ExecutionResult;
import org.neo4j.graphdb.Direction;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Relationship;
import org.neo4j.graphdb.RelationshipType;
import org.neo4j.graphdb.Transaction;
import org.neo4j.graphdb.factory.GraphDatabaseFactory;
import org.neo4j.helpers.collection.IteratorUtil;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.sql.*;
public class NeoProcessor {
//private GraphDatabaseService handle;
private static final String DB_PATH = "/usr/local/Cellar/neo4j/2.0.1/libexec/data/new_graph.db";
static GraphDatabaseService graphDb = new GraphDatabaseFactory().newEmbeddedDatabase( DB_PATH );
public NeoProcessor()
{
}
public void myQuery(String cypherText)
{
//System.out.println("executing the above query");
cypherText = "MATCH (n:Phone{id:'you'}) MATCH n-[r:calling]->m WHERE n<>m RETURN n, r, m";
ExecutionEngine engine = new ExecutionEngine( this.graphDb );
ExecutionResult result;
try ( Transaction ignored = graphDb.beginTx() )
{
result = engine.execute( cypherText + ";");
System.out.println(result);
ignored.success();
}
}
}
Below is a pic showing how the query rreturns results from the DB:

result = engine.execute(cypherText + ";");
System.out.println(result.dumpToString());
Specified by:
http://api.neo4j.org/2.0.3/org/neo4j/cypher/javacompat/ExecutionResult.html#dumpToString()

To consume the result you need to use the iterator. If you just want a string representation use the ExecutionResult.dumpToString(). Be aware this method exhausts the iterator.

You should be calling:
System.out.println(result.dumpToString)
Which will prettify it for you. Of course, there is always the possibility that your match returns no results. You shouuld also close the transaction in a finally block, although that won't matter much here.
EDIT: Taking a second look at this, your Cypher query is wrongly formed, It should be
MATCH (n:Phone) - [r:calling] -> (m)
WHERE n.id = `you'
RETURN n, r, m

Related

QueryParser short cannot be dereferenced

i have some indexed docs and i wanna search in them using a query, i checked lucene documentation and made this code but somehow im getting "short cannot be dereferenced" in the QueryParser line, Im new to Java and to Lucene, im using Lucene 5.3.1
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import static java.time.Clock.system;
import javax.management.Query;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.core.KeywordAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.FuzzyQuery;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import static sun.rmi.transport.TransportConstants.Version;
import static sun.rmi.transport.TransportConstants.Version;
public class Searcher
{
public static void main(String args[]) throws IOException{
String query="computer science";
Analyzer analyzer = new KeywordAnalyzer();
Query q = new QueryParser(Version.LUCENE_CURRENT, "W", analyzer).parse(query); //ERROR IS HERE
Path indexPath = Paths.get("MonIndex");
Directory directory = FSDirectory.open(indexPath);
DirectoryReader reader = DirectoryReader.open(directory);
IndexSearcher iSearcher = new IndexSearcher(reader);
TopDocs topdocs = iSearcher.search(q2, 100);
ScoreDoc[] resultsList = topdocs.scoreDocs;
for(int i = 0; i<resultsList.length; i++){
Document book = iSearcher.doc(resultsList[i].doc);
System.out.println(book.getField("I").stringValue());
}
}
}
The problem is Version.LUCENE_CURRENT. You are not importing Lucene's Version, but you do have sun.rmi.transport.TransportConstants.Version, which, while I'm not familiar with the library, it certainly does appear to be a short. So attempting to dereference that, by attempting to reference the nonexistent sun.rmi.transport.TransportConstants.Version.LUCENE_CURRENT is causing that error to be thrown.
However, in the version of Lucene you say you are using, the QueryParserctor no longer even accepts a Version argument, so just remove it:
Query q = new QueryParser("W", analyzer).parse(query);
Your next error: The Query that the queryparser returns is not a javax.management.Query.

PLS-00103: Encountered the symbol ")"

I am creating a web app which requires connecting to a database and getting the catagories of various types of reports. I am getting a weird error when it comes to executing my SQL via storedproc in java. SELECT * FROM RPT_CTGR; is the sql I submit but when I look at the stack trace it comes back as this:
org.springframework.jdbc.BadSqlGrammarException: CallableStatementCallback; bad SQL grammar [{call SELECT * FROM RPT_CTGR;(?)}]; nested exception is java.sql.SQLException: ORA-06550: line 1, column 38:
PLS-00103: Encountered the symbol ")" when expecting one of the following:
. ( * # % & = - + < / > at in is mod remainder not rem
<an exponent (**)> <> or != or ~= >= <= <> and or like like2
like4 likec as between || indicator multiset member
submultiset
org.springframework.jdbc.support.SQLStateSQLExceptionTranslator.doTranslate(SQLStateSQLExceptionTranslator.java:98)
org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:72)
org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:80)
org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:969)
org.springframework.jdbc.core.JdbcTemplate.call(JdbcTemplate.java:1003)
org.springframework.jdbc.object.StoredProcedure.execute(StoredProcedure.java:144)
org.ifmc.qies.reportaudit.impl.CataImpl.search(CataImpl.java:59)
org.ifmc.qies.reportaudit.web.CataAction.execute(CataAction.java:31)
org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:431)
org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:236)
org.apache.struts.action.ActionServlet.process(ActionServlet.java:1196)
org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:432)
javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
Which for some reason is appending the extra "(?)" to the end of my statement which causes the error. Any ideas?
Code
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import org.ifmc.qies.reportaudit.dao.CataDao;
import org.ifmc.qies.reportaudit.model.Catagory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.SqlOutParameter;
import org.springframework.jdbc.core.SqlParameter;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import oracle.jdbc.OracleTypes;
public class CataImpl extends JdbcDaoSupport implements CataDao {
protected static ApplicationContext ctx = null;
//BaseStoredProcedure extends StoredProcedure
public class CataProc extends BaseStoredProcedure{
public CataProc(DataSource ds, String name) {
super(ds,name);
System.out.println(name);
System.out.println(getSql());
declareParameter(new SqlOutParameter("catagories", OracleTypes.CURSOR,
new RowMapper() {
public Object mapRow(ResultSet rs, int rowNum)
throws SQLException {
Catagory t = new Catagory();
t.setCatId(rs.getString(1));
t.setCat_name(rs.getString(2));
System.out.println(t.getCat_name());
return t;
}
}));
}
}
#Override
public List search() {
String[] paths = {"V:path/to/applicationcontext.xml"};
Map params=new HashMap();
ctx = new FileSystemXmlApplicationContext(paths);
DataSource ds = (DriverManagerDataSource)ctx.getBean("dataSource");
CataProc proc = new CataProc(ds,"SELECT * FROM RPT_CTGR;");
Map results = proc.execute(params);
List catagory = (List)results.get("catagories");
//Test
System.out.println(catagory.get(1).toString());
return catagory;
}
}
I get all my print statements except for the catagories.get(1).toString to return properly the SQL I submitted
You should create a Store Procedure in your Oracle Database which executes your SELECT statement.
You can see this question as reference on how to do it.
E.g.
CREATE OR REPLACE PROCEDURE getCatagories(categories in out sys_refcursor) is
...
SELECT * FROM RPT_CTGR;
...
After that, you need to call the store procedure by its name.
public List search() {
...
DataSource ds = (DriverManagerDataSource) ctx.getBean("dataSource");
CataProc proc = new CataProc(ds,"getCatagories");
Map results = proc.execute(params);
List catagory = (List)results.get("catagories");
...
}

split not working on app engine java and yet works on my Android client

The split method returns spaces and i need to return all elements of the string so i can pick the values i want. it works fine on Android but not on app engine. please help i need the html as an array of strings with no spaces. no this is not a duplicate of the other question. look am using the right regex "\s+"
import com.google.api.server.spi.config.Api;
import com.google.api.server.spi.config.ApiMethod;
import com.google.api.server.spi.config.ApiNamespace;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import javax.inject.Named;
/**
* An endpoint class we are exposing
*/
#Api(name = "myApi", version = "v1", namespace = #ApiNamespace(ownerDomain = "backend.abokiforex.greatcallie.com", ownerName = "backend.abokiforex.greatcallie.com", packagePath = ""))
public class RateEndPoint {
String[] html;
private static final Logger LOG = Logger.getLogger(RateEndPoint.class.getName());
/**
* A simple endpoint method that takes a name and says Hi back
*/
#ApiMethod(name = "getRates")
public MyRates getRates() {
MyRates response = new MyRates();
try {
Document site = Jsoup.connect("http://abokifx.com/").timeout(0).get();
Elements tags = site.select("p");
String txt = tags.text();
html = txt.split("\\s+");
} catch (Exception e) {
e.printStackTrace();
}
for (int i = 0; i < html.length; i++){
LOG.info(html[i] +"\n");
}
response.setValue1(html[18]);
response.setValue2(html[20]);
response.setValue3(html[21]);
response.setValue4(html[23]);
response.setValue5(html[24]);
response.setValue6(html[26]);
response.setValue7(html[97]);
response.setValue8(html[98]);
response.setValue9(html[99]);
response.setValue10(html[70]);
response.setValue11(html[71]);
response.setValue12(html[72]);
return response;
}
}
okay here is the answer. the app engine wasnt using utf-8(unicode) and so it wasnt getting the regex right. i defined it in the appengine-web xml file for it to work

How to load CSV file with cypher in java?

I am new to cypher. I want to load a csv using cypher in java. I googled and found the following piece
LOAD CSV WITH HEADERS FROM "http://neo4j.com/docs/2.3.1/csv/import/movies.csv" AS csvLine
MERGE (country:Country { name: csvLine.country })
.....
How to use this load csv query into java code. I tried something like this.
import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;
import javax.naming.spi.DirStateFactory.Result;
import org.neo4j.cypher.javacompat.ExecutionEngine;
import org.neo4j.cypher.javacompat.ExecutionResult;
import org.neo4j.graphdb.Direction;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Relationship;
import org.neo4j.graphdb.RelationshipType;
import org.neo4j.graphdb.Transaction;
import org.neo4j.graphdb.factory.GraphDatabaseFactory;
import org.neo4j.kernel.impl.util.FileUtils;
public class test_new {
private static final String DB_PATH = "C:...../default.graphdb";
public static void main( final String[] args ) throws IOException
{
GraphDatabaseService db = new GraphDatabaseFactory().newEmbeddedDatabase( DB_PATH );
Transaction tx1 = db.beginTx();
try{
ExecutionEngine engine = new ExecutionEngine(db);
ExecutionResult result = engine.execute("LOAD CSV WITH HEADERS FROM "C:/..../Mock_data.csv" AS csvLine ");
tx1.success();
} finally {
tx1.close();
}
db.shutdown();
}
}
But I am not sure about this line.
ExecutionResult result = engine.execute("LOAD CSV WITH HEADERS FROM "C:/..../Mock_data.csv" AS csvLine ");
It throws syntax error.
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Syntax error, insert ")" to complete MethodInvocation
Syntax error, insert ";" to complete LocalVariableDeclarationStatement
I don't know the syntax construction myself. How to load the csv path?
To correct the Java syntax error, you need to escape double quotes in the middle of the string; otherwise it looks like your string literal finishes at the quote around the path:
"LOAD CSV WITH HEADERS FROM \"C:/..../Mock_data.csv\" AS csvLine "
Finally this Worked for me!!
ExecutionResult result = engine.execute("LOAD CSV WITH HEADERS FROM 'file:///Users/xxxxx/Documents/Txx.csv' AS csvLine ")

example of stardog sparql insert query in java

Can somebody give one java example of sparql insert/Delete query in Stardog.
there is only queryExecution.execSelect() method available.
there is no queryExecution.execInsert() or queryExecution.execDelete() available.
Please give one working example.
EDIT
I've found this this from stardog docs page.
http://stardog.com/docs/#notes
As of 1.1.5, Stardog's SPARQL 1.1 support does not include: UPDATE query language
does that means no way out for editing a tuple once entered?
Stardog does not yet support SPARQL update, but as was pointed out to you on the mailing list, there are 5 ways you can modify the data once it's loaded. You can use our HTTP protocol directly, any of the 3 Java API's we support, or you can use the command line interface.
Below one is a sample program of inserting a graph and removing it.
package com.query;
import java.util.List;
import org.openrdf.model.Graph;
import org.openrdf.model.Statement;
import org.openrdf.model.URI;
import org.openrdf.model.impl.GraphImpl;
import org.openrdf.model.impl.ValueFactoryImpl;
import org.openrdf.query.QueryEvaluationException;
import com.clarkparsia.stardog.StardogDBMS;
import com.clarkparsia.stardog.StardogException;
import com.clarkparsia.stardog.api.Connection;
import com.clarkparsia.stardog.api.ConnectionConfiguration;
import com.clarkparsia.stardog.jena.SDJenaFactory;
import com.hp.hpl.jena.query.ParameterizedSparqlString;
import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.ResultSet;
import com.hp.hpl.jena.query.ResultSetFormatter;
import com.hp.hpl.jena.rdf.model.Model;
public class test {
public static void main(String[] args) throws StardogException, QueryEvaluationException {
String appDbName ="memDb";
String selectQuery="SELECT DISTINCT ?s ?p ?o WHERE { ?s ?p ?o }";
StardogDBMS dbms = StardogDBMS.toServer("snarl://localhost:5820/")
.credentials("admin", "admin".toCharArray()).login();
List<String> dbList = (List<String>) dbms.list();
if (dbList.contains(appDbName)) {
System.out.println("droping " + appDbName);
dbms.drop(appDbName);
}
dbms.createMemory(appDbName);
dbms.logout();
Connection aConn = ConnectionConfiguration
.to("memDb") // the name of the db to connect to
.credentials("admin", "admin") // credentials to use while connecting
.url("snarl://localhost:5820/")
.connect();
Model aModel = SDJenaFactory.createModel(aConn);
System.out.println("################ GRAPH IS EMPTY B4 SUBMITTING ="+aModel.getGraph()+ "################");
URI order = ValueFactoryImpl.getInstance().createURI("RDF:president1");
URI givenName = ValueFactoryImpl.getInstance().createURI("RDF:lincoln");
URI predicate = ValueFactoryImpl.getInstance().createURI("RDF:GivenNane");
Statement aStmt = ValueFactoryImpl.getInstance().createStatement(order,predicate,givenName);
Graph aGraph = new GraphImpl();
aGraph.add(aStmt);
insert(aConn, aGraph);
ParameterizedSparqlString paraQuery = new ParameterizedSparqlString(selectQuery);
QueryExecution qExecution = QueryExecutionFactory.create(paraQuery.asQuery(),aModel);
ResultSet queryResult = qExecution.execSelect();
System.out.println("############### 1 TUPPLE CAME AFTER INSERT ################");
ResultSetFormatter.out(System.out, queryResult);
aGraph.add(aStmt);
remove(aConn, aGraph);
paraQuery = new ParameterizedSparqlString(selectQuery);
qExecution = QueryExecutionFactory.create(paraQuery.asQuery(),aModel);
queryResult = qExecution.execSelect();
System.out.println("################ DB AGAIN EMPTY AFTER REMOVE ################");
ResultSetFormatter.out(System.out, queryResult);
System.out.println("closing connection and model");
aModel.close();
aConn.close();
}
private static void insert(final Connection theConn, final Graph theGraph) throws StardogException {
theConn.begin();
theConn.add().graph(theGraph);
theConn.commit();
}
private static void remove(final Connection theConn, final Graph theGraph) throws StardogException {
theConn.begin();
theConn.remove().graph(theGraph);
theConn.commit();
}
}

Categories