jamesclarke
jamesclarke

Reputation: 83

Neo4j Cypher query results serialisation in Java

I'm building a feed where you have posts, replies etc and I'm trying to get the restricted dataset for a particular feed (within timeframe etc).

I'm calling this query in Java as I'd like to make use of the Java core API for certain tasks whilst having the flexibility to use cypher for more simple queries. Is there any way I can get this in the form of JSON to pass directly back to a web client.

START f=node:feeds(name='MY-FEED')                                     
MATCH (f)<-[:WRITTEN_TO]-(p)<-[:HAS_REPLIED_TO]-(r)<-[:HAS_PUBLISHED]-(ur)
WHERE p.datetime >= 201311261000 AND p.datetime <= 201311271000     
WITH p,collect({m:r.msg,u:ID(ur),dt:r.datetime})[0..2] as prgroup         
MATCH (pu)-[:HAS_PUBLISHED]->(p)<-[t:HAS_TAGGED]-(),                      
()-[l:HAS_LIKED]->(p)                                             
WITH p,pu,prgroup,collect(t.name) as tags,count(l) as likes       
return {                                                                 
    post:{                                                        
        msg:p.msg,                                                 
        id:ID(p),                                                  
        u:ID(pu),                                                  
        dt:p.datetime,                                             
        pin:p.pinned,                                              
        tags:tags,                                                 
        likes:likes                                                 
    },replies:prgroup                                                                                                                     
} as threads                                                      
order by p.pinned desc, p.updated desc                                    
SKIP 0                                                
limit 10                                                                  

In Java (only producing badly formatted json):

ExecutionResult results = engine.execute(cql);
List<String> threads = new ArrayList<String>();
for (Map<String,Object> row : results) {
    for (Object val : row.values()) {
        threads.add(val.toString());
    }
}
return "["+Joiner.on(",").join(threads)+"]";

Any help would be greatly appreciated.

Upvotes: 0

Views: 240

Answers (1)

jamesclarke
jamesclarke

Reputation: 83

Two lines:

Gson g = new GsonBuilder().setPrettyPrinting().create();
String json = g.toJson(IteratorUtil.asList(results.iterator()));

Upvotes: 2

Related Questions