Alex
Alex

Reputation: 5214

Can I write a Neo4j Plugin to intercept and modify CYPHER queries

In my system, I would like to intercept and change Cypher queries as they come in, one alternative is to modify them before sending them from my middle layer to the graph - but is there a way to have a plugin do the conversion for me in the graph itself?

I'd like to do some of the following: If someone identifying themselves as members of group A, imagine I'd like to change their request from:

MATCH(f:Film)-[r:REVIEWED_BY]-(u:User {id:"1337"})

to:

MATCH(p:Product)-[p:PURCHASED_BY]-(u:User {id:"1337"})

Is something like this possible? Or do I have to write the traversals in Java directly to achieve this?

Upvotes: 1

Views: 343

Answers (2)

Max De Marzi
Max De Marzi

Reputation: 1108

Of course you can. You can do ANYTHING in Neo4j. Just grab the cypher string in an unmanaged extension that receives a post request, alter it any way you want, execute it with the graphdb.execute method and return the result as normal.

@POST
@Path("/batch")
public Response alterCypher(String body, @Context GraphDatabaseService db) throws IOException, InterruptedException {

    ArrayList<Result> results = new ArrayList<>();
    // Validate our input or exit right away
    HashMap input = Validators.getValidCypherStatements(body);
    ArrayList<HashMap> statements = (ArrayList<HashMap>)input.get("statements");
    for (HashMap statement : statements) {
        // write the alterQuery method to change the queries.
        String alteredQuery = alterQuery((String)statement.get("statement"));
        Result result = db.execute(alteredQuery, (Map)statement.getOrDefault("parameters", new HashMap<>()));
        results.add(result);
    }
    // or go the results and return them however you want 
    // see https://github.com/dmontag/neo4j-unmanaged-extension-template/blob/master/src/main/java/org/neo4j/example/unmanagedextension/MyService.java#L36
    return Response.ok().build();
}

Upvotes: 4

MicTech
MicTech

Reputation: 45083

At this time it's not possible to extend or modify Cypher queries.

If you need that I recommend you to use Transaction Event API - http://graphaware.com/neo4j/transactions/2014/07/11/neo4j-transaction-event-api.html

With that you should be able to change what query returns.

Upvotes: 1

Related Questions