Skip to content

Gremlinq.Extensions.GroovyScripts   

Introduction

Gremlinq.Extensions.GroovyScripts allows developers to execute Groovy scripts directly within their graph database workflows. This capability enables seamless integration of custom logic and complex operations directly into Gremlin queries. Developers retain the flexibility to deserialize query results into any desired data structure. Also, there is a beautiful fluent API that makes handling variables and variable bindings in queries a lot easier.

Setup

After setting up our NuGet package server with your license key, add the package(s) to your project

.NET CLI
dotnet add package Gremlinq.Extensions.GroovyScripts

//If IAsyncEnumerable extensions like ToArrayAsync are needed, add this package as well (unless already referenced):

dotnet add package System.Linq.Async

In your app's initial setup of IGremlinQuerySource, configure the environment and addd a call to AddGroovyScriptQuerySupport, like shown below:

C#
using static ExRam.Gremlinq.Core.GremlinQuerySource;
using System.Collections.Generic;

// (Incomplete) example provider setup and Gremlinq.Extensions.GroovyScripts setup
var source = g
    .UseGremlinServer<Vertex, Edge>(_ => _
        .AtLocalhost())
   .ConfigureEnvironment(env => env
        .AddGroovyScriptQuerySupport());

Usage example

  • Execution of raw groovy queries:
C#
using static ExRam.Gremlinq.Core.GremlinQuerySource;
using System.Collections.Generic;

await source
    .ExecuteGroovyScript<string>("g.V('personId').has('age', lt(42)).values('name')")
    .ToArrayAsync();
  • To mitigate the risk of injection attacks, it is recommended to pass data through variable bindings. Gremlinq.Extensions.GroovyScripts supports this as well:
C#
using static ExRam.Gremlinq.Core.GremlinQuerySource;
using System.Collections.Generic;

await source
    .ExecuteGroovyScript<string>(
        "g.V(id).has(ageProperty, lt(age)).values(nameProperty)",
        new Dictionary<string, object?>
        {
            { "id", "personId" },
            { "age", 42 },
            { "nameProperty", "name" }
        })
    .ToArrayAsync();
  • A fluent API allows even tighter integration into the C# language. The fluent API allows up to 256 variables:
C#
using static ExRam.Gremlinq.Core.GremlinQuerySource;
using System.Collections.Generic;

await source
    .ExecuteGroovyScript<string>((builder, id, ageProperty, age, nameProperty) => builder
        .WithScript($"g.V({id}).has({ageProperty}, lt({age})).values({nameProperty})")
        .Bind(id.To("personId"))
        .Bind(ageProperty.To("age"))
        .Bind(age.To(42))
        .Bind(nameProperty.To("name")))
    .ToArrayAsync();