neo4j / cypher-dsl

A Java DSL (Builder) for the Cypher Query Language
http://neo4j.github.io/cypher-dsl
Apache License 2.0
192 stars 62 forks source link

Generate only WHERE, with no MATCH or RETURN #1060

Closed HusseinElMotayam closed 2 weeks ago

HusseinElMotayam commented 3 weeks ago

I have a need to build just the WHERE part of a cypher query, without MATCH or RETURN.

I'm looking for something like:

Cypher.name("Product.product_id").matches("BG2");

For which I can get the Cypher equivalent for it to be:

WHERE Product.product_id = 'BG2'

To give more context, it'll be injected into an existing query, which is too hard to re-write in cypher-dsl.

Is there any entry point that can just give me the WHERE part, without going through MATCH and RETURN?

michael-simons commented 2 weeks ago

Hi.

I would do it like this

import static org.assertj.core.api.Assertions.assertThat;

import org.junit.jupiter.api.Test;
import org.neo4j.cypherdsl.core.Cypher;
import org.neo4j.cypherdsl.core.Where;
import org.neo4j.cypherdsl.core.renderer.Configuration;
import org.neo4j.cypherdsl.core.renderer.GeneralizedRenderer;
import org.neo4j.cypherdsl.core.renderer.Renderer;

public class X {
    @Test // GH-1060
    void buildingWhereClauseShouldWork() {

        var node = Cypher.node("Product").named("Product");
        var where = Where.from(node.property("product_id").eq(Cypher.literalOf("BG2")));
        assertThat(where).hasToString("Where{cypher=WHERE Product.product_id = 'BG2'}");

        var cypher = Renderer.getRenderer(Configuration.defaultConfig(), GeneralizedRenderer.class).render(where);
        assertThat(cypher).isEqualTo("WHERE Product.product_id = 'BG2'");
    }
}
HusseinElMotayam commented 2 weeks ago

Much appreciated, thank you!

michael-simons commented 2 weeks ago

You're very welcome, @HusseinElMotayam 🙇