You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@tinkerpop.apache.org by xi...@apache.org on 2026/06/25 15:20:15 UTC
(tinkerpop) branch multi-label-experiment updated (2f26659d8d -> a37c5893c3)
This is an automated email from the ASF dual-hosted git repository.
xiazcy pushed a change to branch multi-label-experiment
in repository https://gitbox.apache.org/repos/asf/tinkerpop.git
discard 2f26659d8d Make TinkerGraph default to ONE for labels, add strategy to throw for unintended drop() usage on labels()
discard 8ff5899a4f multi-label append only update
discard 27da3669c7 Add cardinality
discard 477473f26f GLV implementations
discard ebae853322 implement edge multi-label
discard db8b034c26 fix multi-label in transactions
discard 85df245a2f Add some feature test
discard d7b15faeed add a set of simple feature tests
discard 86b02d945c multilabel prototype
add 910d88f06d Restore ClientBehaviorTests in all GLVs (#3436)
add eadea8a53e Fix ByteBuf leak when IOException thrown during serialization CTR
add 28d8e021e4 Add setting to set CORS allowed origin CTR.
add f5880e73e3 Improve GremlinServer HTTP pipelining behavior CTR.
add ae07eb2d74 Update gremlin-go submit to block until response headers arrive
add 637baaa2dc Add explicit transaction support to non-Java GLVs
add d3b8ca6364 Fix transaction executor thread leak on commit and rollback CTR
add e6551edafc Add an Allow: POST response header for non-POST requests CTR
add 9bc27d1d09 Improve error for divergent transaction "g" value CTR
add 79f853beb7 Map closed transactions to 404 error CTR
add d43ef50b59 Centralize transaction request classification in Context CTR
add 0579a14402 Fixed environmental problems for javascript docker runs CTR
add 4722890ed8 TINKERPOP-3244 Add NextN(n) to Traversal in gremlin-go (3.7-dev)
add 5565acef95 Merge pull request #3430 from L0Lmaker/improvement/TINKERPOP-3244-go-next-n-3.7
add 9ba0b887bd Configure GitHub workflows to use concurrency cancel-in-progress for (#3454)
add 9c7135143b Bump codecov/codecov-action from 6 to 7 (#3452)
add 4e791ed92f Merge branch '3.7-dev' into 3.8-dev
add bded3921c9 Merge branch '3.8-dev'
add 6167becabb Fix up gremlin-go NextN merge CTR
add 6c34b26291 Implement Provider Defined Types (PDT) (#3433)
add 24df1d2b89 TINKERPOP-3250 Standardize request interceptors and switch to JSON request serialization (#3447)
add dd9b90d614 feat: add GQL.g4 minimal ANTLR grammar for MATCH node/edge patterns
add 95b7369ce3 feat: add DeclarativeMatchStep for GQL-based pattern matching
add daf09db8d9 fix: update TinkerGraphGqlPlanner to use canonical GQL.g4 grammar rule names
add f39978c4e4 feat: implement TinkerGraphGqlExecutor with DFS backtracking pattern matching
add c4df599522 feat: implement TinkerGraphMatchStep: executor integration and traverser path binding
add 0a1281e260 feat: add TinkerGraphDeclarativeMatchStrategy optimization strategy
add 733c0da76d feat: add match(String) and match(String, Map) grammar rules to Gremlin.g4
add 5db447f885 feat: add DeclarativeMatchVerificationStrategy to prevent terminal match()
add 9e7e1d6213 feat: add match(String) and match(String, Map) spawn methods to GraphTraversalSource
add a1ca0ac08a feat: add match(String) spawn method to Python GLV and integration test
add 33b6bd65e0 feat: add match(String) and match(String, Map) to JS GLV and integration test
add 0a9742e451 feat: add Match(string) and Match(string, IDictionary) overloads to gremlin-dotnet DSL
add 403e5d24e3 feat: add match(String) support to gremlin-go GLV with integration test
add 19d6d4029c feat: add match(String) and match(String,Map) to grammar visitors
add c40bff9ade fix: update TinkerGraphMatchStepTest to not use match() as terminal step
add e433328283 Fix broken translations
add acc2b96697 fix: code review — bugs, per-graph singletons, tests, and translations
add ea623deef0 Fixed up match() start step
add 04a10f58ef Renamed parameter names
add 8257bb048a refactor: remove DEFAULT_QUERY_LANGUAGE from DeclarativeMatchStep — let graph providers own their language
add f9c0857e9e rename gqlQuery to matchQuery across gremlin-core and all GLVs
add 40c9d0d097 Added documentation for match step
add 9a4b12de5d GQL engine: label/edge count indexes, DAG executor, live seed selection
add af67f481bc refactor: array bindings + lazy Iterator delivery in GQL executor
add bc29cc8a2e feat: GQL property filters — inline map syntax and parameter references
add f074a1ddb9 feat: use TinkerGraph vertex index as seed source for property-filtered GQL patterns
add 5a4aee65eb refactor: deduplicate parallel anonymous edges in GQL DFS executor
add b747a2093d docs: document GQL property filter and parameterized query syntax
add 2cd2fb6ab2 feat: align GQL property filter literal types with Gremlin's type system
add 2836034e4c refactor: rename QueryNode to QueryVertex to align with TinkerPop vertex terminology
add 872a42b7a6 feat: property-aware step cost, best-eligible DAG selection, and adaptive reordering
add 9040f13780 fix: evaluate edge property filter predicates in GQL executor
add 5e5a6263e9 fix: replace unbounded ConcurrentHashMap plan cache with Caffeine LRU cache
add 70a968d1da test: add gremlin-js integration tests for declarative match(String) against TinkerGraph
add 93d5978ac6 docs: document edge property filters and update plan cache note
add 010a0ff7e1 fix: close GQL blindspots — variable conflicts, edge equality, plan staleness, NPE
add 26dd52767c Added benchmarks for match()
add 4196fa76ff fix: merge predicates and allow label refinement for reused node variables in GQL MATCH
add 758478ea1e fix: use any-value-matches semantics for multi-properties in GQL predicate evaluation
add 885dd01526 test: add edge-case coverage for GQL property predicate and match() params
add 8e010bb868 Updated documentation for GQL/TinkerGraph
add 79d3287cb4 fix: match(String) returns binding Map instead of Optional.empty
add da7e5c80f9 fix: correct mock strategy in JS match-test to use _resultsStream
add 6a70546231 Documentation improvements for match after moving out Optional
add b3e3f824e6 test: add executor coverage for Byte, Short, BigInteger, BigDecimal, and Double-d suffix literals
add 93ef1b1a5b Adjust GLV tests gien change to match() returning Map
add 7eb4f799bd docs: add Proposal 10 — Generalized GQL Execution Engine (gql-gremlin module)
add 848f5d0266 docs: revise Proposal 10 — replace GraphStatistics/IndexAccess interfaces with Graph default methods
add ec08d1933e feat: implement Proposal 10 — extract gql-gremlin module with generalized GQL execution engine
add 398532a50e docs: brand TinkerGQL, add gql-gremlin module docs and provider guide
add 889437871c refactor: centralize GQL planner/executor cache in GqlDeclarativeMatchStrategy
add 61f6b0a44a Provide a way to configure the cache for the planner explicitly
add 18a0a71318 docs: fix provider guide, upgrade notes, and reference docs for gql-gremlin refactor
add 3a3a129dac test: add Gherkin coverage for match(String) / TinkerGQL; remove language-variant smoke tests
add b05eb9c7ff test: expand TinkerGQL Gherkin coverage and fix OLAP test exclusion
add 3564eb748f fix: add GLV translator support for match(String, Map) form in Python, .NET, and Go
add 66a808fa04 fix: exclude @TinkerGQL scenarios from Hadoop feature test run
add 41a76ec708 test: verify match(String) wire-protocol round-trip and add cyclic/no-match Gherkin scenarios
add f8331bfeba feat: guard against path-label/pattern-variable name collision in match()
add 9cb9b91ebf refactor: polish match() PR — constant, docs, test consolidation
add 2030bffc9b fix: add DeprecationWarning to Python match(Traversal) form
add c1eaa11836 test: add Gherkin scenarios for multi-pattern bridge join and combined edge variable + filter
add 6315dfc021 fix: address PR review feedback on match() GQL parsing and Go translation
add 0a66f164b6 refactor: migrate GQL parser unit tests from tinkergraph-gremlin to gql-gremlin
add b723d458b1 refactor: replace MatchWithParams with variadic Match on GraphTraversalSource in Go
add 065a6ae71e Make Tree no longer extend HashMap (#3448)
add ad894eba6e Updated examples using old match() syntax
add 01efb1e207 Add graph-based PR review skill (tinker-review)
add 2fd3d45515 Align tinker-dev skill references and add stale-skill cleanup to agent-setup.sh
add 32fdda6b4b TINKERPOP-3204 Extract type-discovery 'unknown' into a constant
add 98f06de01b Skip 1+1 init probe for grammar-based groovy-test engine CTR
add 09bddc9efb Centralize HTTP response writes in HttpResponseCoordinator.
add 8676ca9c86 Ensure enqueued transactions return errors.
add 441a2ca760 Merge pull request #3457
add 5927aeca31 Tighten the tinker-dev skill around a mandatory validation gate
add d9c493fb3a Bring back Tinkubator
add 079a1f093a Added missing license header CTR
add 509d969633 Remove executable example from upgrade docs CTR
add d1a4c00044 Add tinker-doc skill for authoring and reviewing documentation
add a509d25823 fix(gremlin-js): bump uuid from ^9.0.1 to ^11.1.1 to fix GHSA-w5hq-g745-h8pq (#3459)
add 37d9d76f0d build(deps): bump actions/checkout from 6 to 7 (#3470)
add c6df992782 Merge branch '3.7-dev' into 3.8-dev
add 30108994e4 Merge branch '3.8-dev'
add 3c67342a59 build(deps): bump undici from 7.25.0 to 7.28.0 in /gremlin-js (#3477)
add 3765749b79 Remove references to GraphSON4. (#3479)
add 417dfe92e8 build(deps): bump hono from 4.12.14 to 4.12.26 in /gremlin-js (#3478)
add 3b847d771c Terminate the chunked response on serializer failure CTR
add 4e64fcbb65 Release pooled ByteBuf when a TypeSerializer throws unchecked CTR
add 5ad67238f7 Route exceptionCaught through the response coordinator CTR
add e9a1d6f17a TINKERPOP-3243 Add next(n) batch iteration to gremlin-javascript
add fa67cb8245 Merge branch 'TINKERPOP-3243' into 3.7-dev
add 534eb1d4a6 Merge branch '3.7-dev' into 3.8-dev
add e652352dbc Merge branch '3.8-dev'
add a47b821703 TINKERPOP-3179 Add WithComputer() to GraphTraversalSource in gremlin-go
add a867920dc2 Merge branch 'TINKERPOP-3179' into 3.7-dev
add 50c5b01921 Merge branch '3.7-dev' into 3.8-dev
add be19534d73 Merge branch '3.8-dev'
add 88b222949c TINKERPOP-3238 Throw FailResponseException for fail() step over remote
add 1c4ff6aae3 Merge branch 'TINKERPOP-3238' into 3.7-dev
add 213609d4ff Merge branch '3.7-dev' into 3.8-dev
add a76c72a3f6 Merge branch '3.8-dev'
add 7aed918320 Fix 3.7-dev to master merge issue with go test CTR
add 974bbdb3c1 Remove obsolete GType GraphBinary4 serialization CTR
add 790989f3e8 CTR Minor JS Dependency bumps (running npm audit fix)
add 45ed6b3a91 build(deps): bump actions/cache from 5 to 6 (#3481)
add 0dc39a3dbb Merge branch '3.7-dev' into 3.8-dev
add 0f1703bc73 Merge branch '3.8-dev'
new ed4c9ba663 Implement multi-label prototype for vertices
new 511dcd9e47 Extend multi-label to edges, fix transactions, add feature tests
new 0aa9896854 Add GLV implementations for multi-label
new 6a1e99ee33 Add cardinality support and append-only update for multi-label
new a37c5893c3 Make TinkerGraph default to ONE for labels, add docs and changelog
This update added new revisions after undoing existing revisions.
That is to say, some revisions that were in the old version of the
branch are not in the new version. This situation occurs
when a user --force pushes a change and generates a repository
containing something like this:
* -- * -- B -- O -- O -- O (2f26659d8d)
\
N -- N -- N refs/heads/multi-label-experiment (a37c5893c3)
You should already have received notification emails for all of the O
revisions, and so the following emails describe only the N revisions
from the common base, B.
Any revisions marked "omit" are not gone; other references still
refer to them. Any revisions marked "discard" are gone forever.
The 5 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails. The revisions
listed as "add" were already present in the repository and have only
been added to this reference.
Summary of changes:
.dockerignore | 3 +
.github/workflows/build-test.yml | 43 +-
.github/workflows/codeql.yml | 10 +-
.skills/tinker-dev/SKILL.md | 168 +
.../references/beads-workflow.md | 19 -
.../references/dev-environment-setup.md | 26 +-
.skills/tinker-dev/references/gremlin-mcp.md | 70 +
.../scripts/check-env.sh | 2 +-
.skills/tinker-doc/SKILL.md | 134 +
.../tinker-doc/references/asciidoc-and-wiring.md | 154 +
.skills/tinker-doc/references/books-and-voice.md | 320 ++
.skills/tinker-doc/references/executable-blocks.md | 91 +
.skills/tinker-review/.gitignore | 2 +
.skills/tinker-review/SKILL.md | 194 ++
.../tinker-review}/package-lock.json | 50 +-
.skills/tinker-review/package.json | 19 +
.skills/tinker-review/playbooks/bug-fix.md | 47 +
.skills/tinker-review/playbooks/driver-server.md | 67 +
.skills/tinker-review/playbooks/general.md | 52 +
.skills/tinker-review/playbooks/glv.md | 55 +
.skills/tinker-review/playbooks/grammar.md | 37 +
.skills/tinker-review/playbooks/new-step.md | 49 +
.skills/tinker-review/references/interfaces.md | 358 +++
.skills/tinker-review/references/schema.md | 86 +
.../tinker-review/scripts/discovery/discussions.js | 280 ++
.skills/tinker-review/scripts/enrichment/api.js | 168 +
.skills/tinker-review/scripts/enrichment/cli.js | 156 +
.../scripts/extraction/tree-sitter.js | 592 ++++
.../scripts/graph/populate-discussions.js | 279 ++
.skills/tinker-review/scripts/graph/populate.js | 170 ++
.../tinker-review/scripts/infrastructure/docker.js | 128 +
.../tinker-review/scripts/patterns/architecture.js | 161 +
.../tinker-review/scripts/patterns/blast-radius.js | 93 +
.../tinker-review/scripts/patterns/centrality.js | 100 +
.../scripts/patterns/cluster-analysis.js | 71 +
.../tinker-review/scripts/patterns/completeness.js | 93 +
.../scripts/patterns/coverage-gaps.js | 69 +
.skills/tinker-review/scripts/patterns/orphans.js | 74 +
.skills/tinker-review/scripts/renderer/render.js | 422 +++
.../tinker-review/scripts/renderer/template.html | 73 +
.skills/tinker-review/scripts/review.js | 406 +++
.skills/tinkerpop-dev/SKILL.md | 164 -
.skills/tinkerpop-dev/references/build-dotnet.md | 97 -
.skills/tinkerpop-dev/references/build-go.md | 111 -
.skills/tinkerpop-dev/references/build-java.md | 67 -
.../tinkerpop-dev/references/build-javascript.md | 171 --
.skills/tinkerpop-dev/references/build-python.md | 127 -
.skills/tinkerpop-dev/references/documentation.md | 45 -
.skills/tinkerpop-dev/references/gremlin-mcp.md | 159 -
AGENTS.md | 30 +-
CHANGELOG.asciidoc | 27 +-
bin/agent-setup.sh | 113 +-
docker/gremlin-test-server/Dockerfile | 1 +
docs/site/home/gremlin.html | 51 +
docs/site/home/index.html | 9 +
.../dev/developer/development-environment.asciidoc | 2 +-
docs/src/dev/developer/for-committers.asciidoc | 10 +-
.../dev/future/proposal-3-remove-closures.asciidoc | 7 +-
.../dev/future/proposal-arrow-flight-2.asciidoc | 2 +-
.../src/dev/future/proposal-asbool-step-7.asciidoc | 2 +-
.../dev/future/proposal-asnumber-step-6.asciidoc | 2 +-
.../proposal-declarative-match-step-9.asciidoc | 4 +
docs/src/dev/future/proposal-equality-1.asciidoc | 2 +-
docs/src/dev/future/proposal-scoping-5.asciidoc | 2 +-
.../src/dev/future/proposal-transaction-4.asciidoc | 2 +-
.../dev/future/proposal-type-predicate-8.asciidoc | 2 +-
docs/src/dev/provider/gremlin-semantics.asciidoc | 139 +
docs/src/dev/provider/index.asciidoc | 413 +++
docs/src/recipes/duplicate-edge.asciidoc | 12 +-
docs/src/reference/gremlin-applications.asciidoc | 6 +-
docs/src/reference/gremlin-variants.asciidoc | 673 +++-
.../reference/implementations-tinkergraph.asciidoc | 66 +
docs/src/reference/intro.asciidoc | 2 -
docs/src/reference/the-traversal.asciidoc | 649 ++--
docs/src/upgrade/release-3.7.x.asciidoc | 17 +
docs/src/upgrade/release-4.x.x.asciidoc | 3218 +++++++++++---------
gql-gremlin/README.md | 67 +
{gremlin-language => gql-gremlin}/pom.xml | 58 +-
gql-gremlin/src/main/antlr4/GQL.g4 | 311 ++
.../tinkerpop/gremlin/gql/DefaultGqlExecutor.java | 318 ++
.../tinkerpop/gremlin/gql/DefaultGqlPlanner.java | 339 +++
.../tinkerpop/gremlin/gql/ExtensionStep.java | 207 ++
.../gremlin/gql/GqlDeclarativeMatchStrategy.java | 210 ++
.../apache/tinkerpop/gremlin/gql/GqlExecutor.java | 79 +
.../apache/tinkerpop/gremlin/gql/GqlMatchPlan.java | 160 +
.../apache/tinkerpop/gremlin/gql/GqlMatchStep.java | 260 ++
.../apache/tinkerpop/gremlin/gql/GqlPlanner.java | 71 +
.../tinkerpop/gremlin/gql/PropertyPredicate.java | 162 +
.../apache/tinkerpop/gremlin/gql/QueryEdge.java | 129 +
.../apache/tinkerpop/gremlin/gql/QueryGraph.java | 387 +++
.../apache/tinkerpop/gremlin/gql/QueryVertex.java | 89 +
.../tinkerpop/gremlin/gql/GqlGrammarTest.java | 267 ++
.../tinkerpop/gremlin/gql/QueryGraphTest.java | 364 +++
.../grammar/DefaultGremlinBaseVisitor.java | 22 +-
.../language/grammar/GenericLiteralVisitor.java | 17 +
.../language/grammar/TraversalMethodVisitor.java | 19 +-
.../grammar/TraversalSourceSpawnMethodVisitor.java | 17 +
.../translator/AnonymizedTranslatorVisitor.java | 6 +
.../translator/DotNetTranslateVisitor.java | 58 +-
.../language/translator/GoTranslateVisitor.java | 55 +
.../translator/GroovyTranslateVisitor.java | 10 +
.../language/translator/JavaTranslateVisitor.java | 10 +
.../translator/JavascriptTranslateVisitor.java | 10 +
.../translator/PythonTranslateVisitor.java | 22 +-
.../language/translator/TranslateVisitor.java | 6 +
.../gremlin/process/remote/RemoteConnection.java | 9 +
.../gremlin/process/traversal/Failure.java | 105 +-
.../gremlin/process/traversal/GremlinLang.java | 45 +
.../traversal/dsl/graph/GraphTraversal.java | 36 +
.../traversal/dsl/graph/GraphTraversalSource.java | 41 +
.../gremlin/process/traversal/dsl/graph/__.java | 18 +
.../process/traversal/step/map/CountLocalStep.java | 4 +-
.../traversal/step/map/DeclarativeMatchStep.java | 159 +
.../process/traversal/step/map/ElementMapStep.java | 12 +-
.../process/traversal/step/map/MatchStep.java | 3 +
.../traversal/step/map/PropertyMapStep.java | 8 +-
.../process/traversal/step/map/TreeStep.java | 4 +-
.../step/sideEffect/TreeSideEffectStep.java | 4 +-
.../gremlin/process/traversal/step/util/Tree.java | 285 +-
.../process/traversal/step/util/WithOptions.java | 17 +-
.../apache/tinkerpop/gremlin/structure/Graph.java | 82 +
.../gremlin/structure/LabelCardinality.java | 101 +-
.../gremlin/structure/io/binary/DataType.java | 4 +-
.../gremlin/structure/io/binary/GraphBinaryIo.java | 60 -
.../structure/io/binary/GraphBinaryReader.java | 21 +-
.../structure/io/binary/GraphBinaryWriter.java | 20 +-
.../io/binary/TypeSerializerRegistry.java | 95 +-
.../io/binary/types/CustomTypeSerializer.java | 32 -
.../structure/io/binary/types/EnumSerializer.java | 2 -
...zer.java => ProviderDefinedTypeSerializer.java} | 39 +-
.../structure/io/binary/types/TreeSerializer.java | 11 +-
.../structure/io/graphson/GraphSONMapper.java | 17 +
.../structure/io/graphson/GraphSONModule.java | 12 +
.../io/graphson/GraphSONSerializersV1.java | 14 +-
.../io/graphson/GraphSONSerializersV2.java | 15 +-
.../io/graphson/GraphSONSerializersV3.java | 14 +-
.../io/graphson/GraphSONSerializersV4.java | 14 +-
.../io/graphson/PdtGraphSONSerializersV4.java | 116 +
.../structure/io/gryo/GryoSerializersV1.java | 25 +
.../structure/io/gryo/GryoSerializersV3.java | 25 +
.../gremlin/structure/io/gryo/GryoVersion.java | 4 +-
.../gremlin/structure/io/pdt/ProviderDefined.java | 14 +-
.../structure/io/pdt/ProviderDefinedType.java | 186 ++
.../io/pdt/ProviderDefinedTypeAdapter.java | 15 +-
.../io/pdt/ProviderDefinedTypeRegistry.java | 224 ++
.../structure/util/LabelCardinalityValidator.java | 104 +
.../structure/util/detached/DetachedFactory.java | 16 +-
.../structure/util/reference/ReferenceFactory.java | 16 +-
.../grammar/GeneralLiteralVisitorTest.java | 41 +
.../grammar/TraversalMethodVisitorTest.java | 15 +
.../grammar/TraversalSourceSpawnVisitorTest.java | 17 +
.../language/translator/GremlinTranslatorTest.java | 27 +
.../gremlin/process/traversal/FailureTest.java | 101 +
.../gremlin/process/traversal/GremlinLangTest.java | 98 +
.../traversal/step/map/CountLocalStepTest.java | 34 +
.../process/traversal/step/util/TreeTest.java | 251 +-
.../io/graphson/PdtGraphSONSerializersV4Test.java | 230 ++
.../io/pdt/ProviderDefinedTypeRegistryTest.java | 416 +++
.../structure/io/pdt/ProviderDefinedTypeTest.java | 227 ++
.../gremlin/util/function/TreeSupplierTest.java | 4 +-
gremlin-dotnet/docker-compose.yml | 16 +-
gremlin-dotnet/src/Gremlin.Net/Driver/Auth.cs | 5 +-
.../src/Gremlin.Net/Driver/Connection.cs | 54 +-
.../src/Gremlin.Net/Driver/GremlinClient.cs | 119 +-
.../src/Gremlin.Net/Driver/HttpRequestContext.cs | 54 +-
.../src/Gremlin.Net/Driver/IMessageSerializer.cs | 17 +-
.../Driver/Remote/DriverRemoteConnection.cs | 32 +-
.../Driver/Remote/TransactionRemoteConnection.cs | 110 +
.../src/Gremlin.Net/Driver/RemoteTransaction.cs | 271 ++
gremlin-dotnet/src/Gremlin.Net/Driver/Tokens.cs | 5 +
.../Process/Remote/IRemoteConnection.cs | 8 +-
.../Process/Remote/RemoteTransaction.cs | 87 -
.../Process/Traversal/AnonymousTraversalSource.cs | 2 +-
.../Process/Traversal/GraphSONVersion.cs | 66 -
.../Process/Traversal/GraphTraversal.cs | 25 +
.../Process/Traversal/GraphTraversalSource.cs | 42 +-
.../Gremlin.Net/Process/Traversal/GremlinLang.cs | 91 +-
.../src/Gremlin.Net/Process/Traversal/__.cs | 24 +-
.../Structure/IO/GraphBinary4/DataType.cs | 2 +-
.../GraphBinary4/GraphBinary4MessageSerializer.cs | 21 +-
.../Structure/IO/GraphBinary4/GraphBinaryReader.cs | 19 +-
.../IO/GraphBinary4/RequestMessageSerializer.cs | 8 +-
.../IO/GraphBinary4/TypeSerializerRegistry.cs | 2 +
.../GraphBinary4/Types/CompositePDTSerializer.cs | 78 +
.../IProviderDefinedTypeAdapter.cs} | 29 +-
.../Structure/ProviderDefinedAttribute.cs | 107 +
.../Gremlin.Net/Structure/ProviderDefinedType.cs | 70 +
.../Structure/ProviderDefinedTypeRegistry.cs | 159 +
.../Docs/Reference/GremlinVariantsTests.cs | 51 +-
.../Driver/ClientBehaviorIntegrationTests.cs | 308 ++
.../Driver/DriverRemoteConnectionTests.cs | 100 +
.../Driver/GremlinClientTests.cs | 157 +
.../Driver/SocketServerConstants.cs} | 35 +-
.../Driver/TransactionTests.cs | 545 ++++
.../Gremlin.Net.IntegrationTest/Gherkin/Gremlin.cs | 30 +-
.../Gremlin.Net.IntegrationTest.csproj | 1 -
.../GraphTraversalTransactionTests.cs | 96 -
.../Util/SocketServerSettings.cs | 94 -
.../Gremlin.Net.UnitTest/Driver/ConnectionTests.cs | 201 +-
.../Driver/DriverRemoteConnectionTests.cs | 6 +-
.../Driver/GremlinClientTests.cs | 22 +-
.../Driver/HttpRequestContextTests.cs | 168 +-
.../Process/Remote/RemoteTransactionTests.cs | 44 -
.../Process/Traversal/GremlinLangTests.cs | 143 +
.../GraphBinary4MessageSerializerTests.cs | 2 +-
.../IO/GraphBinary4/ProviderDefinedTypeTests.cs | 137 +
.../Structure/ProviderDefinedAttributeTests.cs | 216 ++
.../Structure/ProviderDefinedTypeRegistryTests.cs | 242 ++
gremlin-driver/pom.xml | 6 +
.../src/main/java/examples/Connections.java | 7 +-
.../apache/tinkerpop/gremlin/driver/Cluster.java | 103 +-
.../tinkerpop/gremlin/driver/HttpRequest.java | 65 +-
.../gremlin/driver/RequestInterceptor.java | 20 +-
.../tinkerpop/gremlin/driver/auth/Basic.java | 8 +-
.../tinkerpop/gremlin/driver/auth/Sigv4.java | 15 +-
.../driver/exception/FailResponseException.java | 61 +
.../driver/exception/ResponseException.java | 13 +
.../driver/handler/GremlinResponseHandler.java | 2 +-
.../driver/handler/HttpGremlinRequestEncoder.java | 43 +-
.../interceptor/PayloadSerializingInterceptor.java | 73 -
.../driver/remote/DriverRemoteConnection.java | 17 +
.../driver/remote/HttpRemoteTransaction.java | 5 +-
.../gremlin/driver/simple/SimpleHttpClient.java | 6 +-
.../stream/GraphBinaryStreamResponseReader.java | 2 +-
.../driver/ClientBehaviorIntegrateTest.java | 369 +++
.../gremlin/driver/ClusterConfigTest.java | 52 -
.../tinkerpop/gremlin/driver/ClusterTest.java | 143 -
.../tinkerpop/gremlin/driver/InterceptorTest.java | 219 ++
.../tinkerpop/gremlin/driver/auth/Sigv4Test.java | 56 +-
.../exception/FailResponseExceptionTest.java | 83 +
gremlin-examples/gremlin-java/Connections.java | 7 +-
gremlin-go/docker-compose.yml | 15 +
gremlin-go/driver/auth.go | 16 +-
gremlin-go/driver/client.go | 57 +-
gremlin-go/driver/client_behavior_test.go | 253 ++
gremlin-go/driver/client_test.go | 95 +
gremlin-go/driver/connection.go | 156 +-
gremlin-go/driver/connection_test.go | 209 +-
gremlin-go/driver/cucumber/cucumberSteps_test.go | 5 +-
gremlin-go/driver/cucumber/gremlin.go | 30 +-
gremlin-go/driver/driverRemoteConnection.go | 14 +
gremlin-go/driver/error_codes.go | 5 +-
gremlin-go/driver/graphBinaryDeserializer.go | 55 +-
gremlin-go/driver/graphBinaryDeserializer_test.go | 20 -
gremlin-go/driver/graphBinarySerializer.go | 7 +-
gremlin-go/driver/graphBinarySerializer_test.go | 101 +
gremlin-go/driver/graphTraversal.go | 78 +-
gremlin-go/driver/graphTraversalSource.go | 54 +-
gremlin-go/driver/graphTraversalSource_test.go | 26 +
gremlin-go/driver/gremlinlang.go | 44 +-
gremlin-go/driver/gremlinlang_test.go | 145 +
gremlin-go/driver/interceptor.go | 44 +-
gremlin-go/driver/interceptor_test.go | 552 +++-
gremlin-go/driver/pdtRegistry.go | 105 +
gremlin-go/driver/pdtRegistry_test.go | 116 +
gremlin-go/driver/providerDefinedType.go | 51 +
...nection_test.go => providerDefinedType_test.go} | 15 +-
gremlin-go/driver/request.go | 15 +-
gremlin-go/driver/requestOptions.go | 8 +
gremlin-go/driver/request_test.go | 2 +-
gremlin-go/driver/resources/error-messages/en.json | 2 +
gremlin-go/driver/serializer.go | 51 +-
...ion_test.go => socket_server_constants_test.go} | 26 +-
gremlin-go/driver/transaction.go | 197 ++
.../{marker.go => transactionRemoteConnection.go} | 31 +-
gremlin-go/driver/transaction_test.go | 633 ++++
gremlin-go/driver/traversal.go | 2 +-
gremlin-go/driver/traversal_test.go | 417 +--
.../gremlin/groovy/loaders/SugarLoader.groovy | 13 +
.../gremlin/groovy/TreeSubscriptTest.groovy | 68 +
gremlin-js/gremlin-javascript/docker-compose.yml | 16 +-
gremlin-js/gremlin-javascript/lib/driver/auth.ts | 8 +-
gremlin-js/gremlin-javascript/lib/driver/client.ts | 40 +-
.../gremlin-javascript/lib/driver/connection.ts | 68 +-
.../lib/driver/driver-remote-connection.ts | 29 +-
.../gremlin-javascript/lib/driver/http-request.ts | 72 +
.../lib/driver/remote-connection.ts | 20 +-
.../lib/driver/request-message.ts | 38 +
gremlin-js/gremlin-javascript/lib/index.ts | 5 +
.../language/translator/DotNetTranslateVisitor.ts | 34 +-
.../lib/language/translator/GoTranslateVisitor.ts | 38 +
.../language/translator/PythonTranslateVisitor.ts | 12 +-
.../lib/process/anonymous-traversal.ts | 6 +-
.../lib/process/graph-traversal.ts | 51 +-
.../gremlin-javascript/lib/process/gremlin-lang.ts | 21 +-
.../gremlin-javascript/lib/process/transaction.ts | 148 +-
.../gremlin-javascript/lib/process/traversal.ts | 34 +-
.../lib/structure/ProviderDefinedTypeRegistry.ts | 81 +
.../gremlin-javascript/lib/structure/graph.ts | 18 +
.../lib/structure/io/binary/GraphBinary.js | 62 +-
.../structure/io/binary/internals/AnySerializer.js | 1 +
...narySerializer.js => CompositePDTSerializer.js} | 73 +-
.../io/binary/internals/GraphBinaryReader.js | 3 +
gremlin-js/gremlin-javascript/pom.xml | 9 +-
.../gremlin-javascript/test/cucumber/gremlin.js | 30 +-
.../test/integration/client-behavior-tests.js | 149 +
.../test/integration/client-tests.js | 155 +-
.../test/integration/match-tests.js | 82 +
.../test/integration/socket-server-constants.js} | 18 +-
.../test/integration/transaction-tests.js | 424 +++
.../test/integration/traversal-test.js | 208 +-
.../gremlin-javascript/test/unit/auth-test.js | 73 +-
.../test/unit/connection-test.js | 150 +
.../graphbinary/CompositePDTSerializer-test.js | 150 +
.../test/unit/graphbinary/precise-mode-test.js | 2 +-
.../test/unit/gremlin-lang-test.js | 39 +-
.../test/unit/http-request-test.js | 238 ++
.../gremlin-javascript/test/unit/match-test.js | 113 +
.../test/unit/pdt-registry-test.js | 174 ++
.../gremlin-javascript/test/unit/traversal-test.js | 115 +-
gremlin-js/gremlin-mcp/src/constants.ts | 6 +
.../gremlin-mcp/src/gremlin/property-analyzer.ts | 7 +-
gremlin-js/package-lock.json | 1352 ++++----
gremlin-language/src/main/antlr4/Gremlin.g4 | 17 +-
gremlin-python/docker-compose.yml | 15 +
.../src/main/python/examples/connections.py | 2 -
.../gremlin_python/driver/aiohttp/transport.py | 5 -
.../src/main/python/gremlin_python/driver/auth.py | 26 +-
.../main/python/gremlin_python/driver/client.py | 39 +-
.../python/gremlin_python/driver/connection.py | 51 +-
.../driver/driver_remote_connection.py | 15 +-
.../python/gremlin_python/driver/http_request.py | 65 +
.../main/python/gremlin_python/driver/request.py | 3 +-
.../python/gremlin_python/driver/serializer.py | 11 +-
.../python/gremlin_python/driver/transaction.py | 172 ++
.../gremlin_python/process/graph_traversal.py | 127 +-
.../python/gremlin_python/process/traversal.py | 44 +-
.../main/python/gremlin_python/structure/graph.py | 124 +
.../gremlin_python/structure/io/graphbinaryV4.py | 68 +-
.../src/main/python/tests/feature/gremlin.py | 30 +-
.../src/main/python/tests/feature/terrain.py | 2 +-
.../src/main/python/tests/integration/conftest.py | 50 +-
.../integration/driver/socket_server_constants.py | 21 +-
.../python/tests/integration/driver/test_auth.py | 57 +-
.../python/tests/integration/driver/test_client.py | 121 +-
.../integration/driver/test_client_behavior.py | 197 ++
.../driver/test_driver_remote_connection.py | 33 +-
.../tests/integration/driver/test_transaction.py | 412 +++
.../driver/test_web_socket_client_behavior.py | 100 -
.../tests/integration/process/test_traversal.py | 263 --
.../tests/unit/driver/test_http_streaming.py | 77 +-
.../python/tests/unit/driver/test_interceptor.py | 221 ++
.../python/tests/unit/process/test_gremlin_lang.py | 83 +
.../tests/unit/structure/io/test_graphbinaryV4.py | 24 +-
.../structure/io/test_provider_defined_type.py | 243 ++
gremlin-server/conf/gremlin-server.yaml | 2 +
gremlin-server/pom.xml | 16 +
.../apache/tinkerpop/gremlin/server/Context.java | 85 +-
.../apache/tinkerpop/gremlin/server/Settings.java | 16 +
.../gremlin/server/channel/HttpChannelizer.java | 22 +-
.../server/handler/HttpGremlinEndpointHandler.java | 261 +-
.../gremlin/server/handler/HttpHandlerUtil.java | 118 +-
.../server/handler/HttpRequestIdHandler.java | 14 +-
.../server/handler/HttpRequestMessageDecoder.java | 8 +-
.../server/handler/HttpResponseCoordinator.java | 245 ++
.../tinkerpop/gremlin/server/handler/StateKey.java | 13 +-
.../TransactionManager.java | 16 +-
.../UnmanagedTransaction.java | 35 +-
.../gremlin/server/util/GremlinError.java | 15 +
.../gremlin/server/util/ServerGremlinExecutor.java | 7 +-
.../remote/GraphSONLangRemoteFeatureTest.java | 51 -
...GraphSONLangRemoteParameterizedFeatureTest.java | 51 -
.../remote/GraphSONRemoteComputerFeatureTest.java | 51 -
.../gremlin/driver/remote/RemoteWorld.java | 31 -
.../gremlin/server/GremlinDriverIntegrateTest.java | 277 +-
.../GremlinDriverTransactionIntegrateTest.java | 43 +-
.../server/GremlinServerAuthIntegrateTest.java | 9 +-
.../server/GremlinServerHttpIntegrateTest.java | 49 +
.../GremlinServerHttpPipeliningIntegrateTest.java | 72 +
.../GremlinServerHttpTransactionIntegrateTest.java | 79 +-
.../gremlin/server/GremlinServerIntegrateTest.java | 4 +
.../GremlinServerSerializationIntegrateTest.java | 86 +
.../gremlin/server/TestClientFactory.java | 5 -
.../handler/HttpGremlinEndpointHandlerTest.java | 62 +
.../server/handler/HttpRequestIdHandlerTest.java | 25 +
.../tinkerpop/gremlin/server/pdt/Address.java | 20 +-
.../tinkerpop/gremlin/server/pdt/Person.java | 26 +-
.../apache/tinkerpop/gremlin/server/pdt/Point.java | 19 +-
.../io.cucumber.core.backend.ObjectFactory | 3 -
.../apache/tinkerpop/gremlin/LoadGraphWith.java | 19 +-
.../tinkerpop/gremlin/features/StepDefinition.java | 14 +-
.../apache/tinkerpop/gremlin/features/World.java | 2 +-
.../gremlin/language/translator/translations.json | 642 +++-
.../gremlin/structure/io/gryo/air-routes-v3.kryo | Bin
.../gremlin/test/features/map/Labels.feature | 14 -
.../gremlin/test/features/map/MatchString.feature | 322 ++
.../gremlin/test/features/map/MergeVertex.feature | 44 +-
.../test/features/sideEffect/DropLabel.feature | 17 +
.../gremlin/test/features/sideEffect/Tree.feature | 20 +-
gremlin-tools/gremlin-benchmark/pom.xml | 2 +-
.../benchmark/util/AbstractGraphBenchmark.java | 2 +
.../gremlin/process/MatchStepBenchmark.java | 295 ++
gremlin-tools/gremlin-socket-server/Dockerfile | 1 -
.../conf/test-ws-gremlin.yaml | 56 -
...mpleSocketServer.java => SimpleTestServer.java} | 10 +-
.../socket/server/SocketServerConstants.java | 40 +
.../gremlin/socket/server/SocketServerRunner.java | 20 +-
.../socket/server/SocketServerSettings.java | 93 -
.../gremlin/socket/server/TestHandlers.java | 48 -
.../socket/server/TestHttpGremlinHandler.java | 229 ++
.../socket/server/TestHttpServerInitializer.java | 20 +-
.../gremlin/util/message/RequestMessage.java | 9 +
.../util/ser/GraphBinaryMessageSerializerV4.java | 75 +-
.../gremlin/util/ser/AbstractRoundTripTest.java | 8 +-
.../binary/GraphBinaryMessageSerializerV4Test.java | 20 +
.../binary/GraphBinaryPdtSpiAutoWiringTest.java | 134 +
.../util/ser/binary/GraphBinaryWriterPdtTest.java | 94 +
.../gremlin/util/ser/binary/TestPointAdapter.java | 63 +
.../ser/binary/TypeSerializerFailureTests.java | 2 +-
.../ser/binary/TypeSerializerRegistryTest.java | 10 +-
.../types/ProviderDefinedTypeSerializerTest.java | 232 ++
.../util/ser/binary/types/sample/SamplePerson.java | 46 -
.../types/sample/SamplePersonSerializer.java | 117 -
.../types/sample/SamplePersonSerializerTest.java | 126 -
...lin.structure.io.pdt.ProviderDefinedTypeAdapter | 1 +
.../hadoop/HadoopGraphFeatureIntegrateTest.java | 2 +-
pom.xml | 7 +-
tinkergraph-gremlin/pom.xml | 10 +
.../tinkergraph/structure/AbstractTinkerGraph.java | 64 +-
.../gremlin/tinkergraph/structure/TinkerEdge.java | 9 +-
.../gremlin/tinkergraph/structure/TinkerGraph.java | 36 +-
.../tinkergraph/structure/TinkerIndexHelper.java | 4 +
.../structure/TinkerTransactionGraph.java | 20 +-
.../tinkergraph/structure/TinkerVertex.java | 11 +-
.../gremlin/gql/DefaultGqlExecutorTest.java | 1194 ++++++++
.../gremlin/gql/DefaultGqlPlannerTest.java | 451 +++
.../traversal/step/map/GqlMatchStepTest.java | 528 ++++
.../process/traversal/step/map/LabelsStepTest.java | 15 -
.../step/sideEffect/LabelMutationPropertyTest.java | 6 +-
.../step/sideEffect/LabelMutationStepTest.java | 52 +-
.../GqlDeclarativeMatchStrategyTest.java | 219 ++
.../structure/LabelCardinalityTest.java | 78 -
.../LabelReplacePatternValidationTest.java | 54 -
.../structure/MergeOnMatchLabelPatternsTest.java | 172 --
.../tinkergraph/structure/TinkerShuffleGraph.java | 9 +
.../TinkerVertexMultiLabelGremlinLangTest.java | 13 -
tinkubator/README.md | 59 +
437 files changed, 34305 insertions(+), 8744 deletions(-)
create mode 100644 .skills/tinker-dev/SKILL.md
rename .skills/{tinkerpop-dev => tinker-dev}/references/beads-workflow.md (91%)
rename .skills/{tinkerpop-dev => tinker-dev}/references/dev-environment-setup.md (78%)
create mode 100644 .skills/tinker-dev/references/gremlin-mcp.md
rename .skills/{tinkerpop-dev => tinker-dev}/scripts/check-env.sh (98%)
create mode 100644 .skills/tinker-doc/SKILL.md
create mode 100644 .skills/tinker-doc/references/asciidoc-and-wiring.md
create mode 100644 .skills/tinker-doc/references/books-and-voice.md
create mode 100644 .skills/tinker-doc/references/executable-blocks.md
create mode 100644 .skills/tinker-review/.gitignore
create mode 100644 .skills/tinker-review/SKILL.md
copy {gremlin-examples/gremlin-javascript => .skills/tinker-review}/package-lock.json (78%)
create mode 100644 .skills/tinker-review/package.json
create mode 100644 .skills/tinker-review/playbooks/bug-fix.md
create mode 100644 .skills/tinker-review/playbooks/driver-server.md
create mode 100644 .skills/tinker-review/playbooks/general.md
create mode 100644 .skills/tinker-review/playbooks/glv.md
create mode 100644 .skills/tinker-review/playbooks/grammar.md
create mode 100644 .skills/tinker-review/playbooks/new-step.md
create mode 100644 .skills/tinker-review/references/interfaces.md
create mode 100644 .skills/tinker-review/references/schema.md
create mode 100644 .skills/tinker-review/scripts/discovery/discussions.js
create mode 100644 .skills/tinker-review/scripts/enrichment/api.js
create mode 100644 .skills/tinker-review/scripts/enrichment/cli.js
create mode 100644 .skills/tinker-review/scripts/extraction/tree-sitter.js
create mode 100644 .skills/tinker-review/scripts/graph/populate-discussions.js
create mode 100644 .skills/tinker-review/scripts/graph/populate.js
create mode 100644 .skills/tinker-review/scripts/infrastructure/docker.js
create mode 100644 .skills/tinker-review/scripts/patterns/architecture.js
create mode 100644 .skills/tinker-review/scripts/patterns/blast-radius.js
create mode 100644 .skills/tinker-review/scripts/patterns/centrality.js
create mode 100644 .skills/tinker-review/scripts/patterns/cluster-analysis.js
create mode 100644 .skills/tinker-review/scripts/patterns/completeness.js
create mode 100644 .skills/tinker-review/scripts/patterns/coverage-gaps.js
create mode 100644 .skills/tinker-review/scripts/patterns/orphans.js
create mode 100644 .skills/tinker-review/scripts/renderer/render.js
create mode 100644 .skills/tinker-review/scripts/renderer/template.html
create mode 100644 .skills/tinker-review/scripts/review.js
delete mode 100644 .skills/tinkerpop-dev/SKILL.md
delete mode 100644 .skills/tinkerpop-dev/references/build-dotnet.md
delete mode 100644 .skills/tinkerpop-dev/references/build-go.md
delete mode 100644 .skills/tinkerpop-dev/references/build-java.md
delete mode 100644 .skills/tinkerpop-dev/references/build-javascript.md
delete mode 100644 .skills/tinkerpop-dev/references/build-python.md
delete mode 100644 .skills/tinkerpop-dev/references/documentation.md
delete mode 100644 .skills/tinkerpop-dev/references/gremlin-mcp.md
create mode 100644 gql-gremlin/README.md
copy {gremlin-language => gql-gremlin}/pom.xml (59%)
create mode 100644 gql-gremlin/src/main/antlr4/GQL.g4
create mode 100644 gql-gremlin/src/main/java/org/apache/tinkerpop/gremlin/gql/DefaultGqlExecutor.java
create mode 100644 gql-gremlin/src/main/java/org/apache/tinkerpop/gremlin/gql/DefaultGqlPlanner.java
create mode 100644 gql-gremlin/src/main/java/org/apache/tinkerpop/gremlin/gql/ExtensionStep.java
create mode 100644 gql-gremlin/src/main/java/org/apache/tinkerpop/gremlin/gql/GqlDeclarativeMatchStrategy.java
create mode 100644 gql-gremlin/src/main/java/org/apache/tinkerpop/gremlin/gql/GqlExecutor.java
create mode 100644 gql-gremlin/src/main/java/org/apache/tinkerpop/gremlin/gql/GqlMatchPlan.java
create mode 100644 gql-gremlin/src/main/java/org/apache/tinkerpop/gremlin/gql/GqlMatchStep.java
create mode 100644 gql-gremlin/src/main/java/org/apache/tinkerpop/gremlin/gql/GqlPlanner.java
create mode 100644 gql-gremlin/src/main/java/org/apache/tinkerpop/gremlin/gql/PropertyPredicate.java
create mode 100644 gql-gremlin/src/main/java/org/apache/tinkerpop/gremlin/gql/QueryEdge.java
create mode 100644 gql-gremlin/src/main/java/org/apache/tinkerpop/gremlin/gql/QueryGraph.java
create mode 100644 gql-gremlin/src/main/java/org/apache/tinkerpop/gremlin/gql/QueryVertex.java
create mode 100644 gql-gremlin/src/test/java/org/apache/tinkerpop/gremlin/gql/GqlGrammarTest.java
create mode 100644 gql-gremlin/src/test/java/org/apache/tinkerpop/gremlin/gql/QueryGraphTest.java
create mode 100644 gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/DeclarativeMatchStep.java
delete mode 100644 gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/io/binary/GraphBinaryIo.java
delete mode 100644 gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/io/binary/types/CustomTypeSerializer.java
copy gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/io/binary/types/{BulkSetSerializer.java => ProviderDefinedTypeSerializer.java} (50%)
create mode 100644 gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/io/graphson/PdtGraphSONSerializersV4.java
copy gremlin-test/src/main/java/org/apache/tinkerpop/gremlin/jsr223/ScriptEngineToTest.java => gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/io/pdt/ProviderDefined.java (74%)
create mode 100644 gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/io/pdt/ProviderDefinedType.java
copy docs/upgrade/java/src/main/java/org/apache/tinkerpop/example/cmdb/domain/PathDto.java => gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/io/pdt/ProviderDefinedTypeAdapter.java (70%)
create mode 100644 gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/io/pdt/ProviderDefinedTypeRegistry.java
create mode 100644 gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/util/LabelCardinalityValidator.java
create mode 100644 gremlin-core/src/test/java/org/apache/tinkerpop/gremlin/process/traversal/FailureTest.java
create mode 100644 gremlin-core/src/test/java/org/apache/tinkerpop/gremlin/structure/io/graphson/PdtGraphSONSerializersV4Test.java
create mode 100644 gremlin-core/src/test/java/org/apache/tinkerpop/gremlin/structure/io/pdt/ProviderDefinedTypeRegistryTest.java
create mode 100644 gremlin-core/src/test/java/org/apache/tinkerpop/gremlin/structure/io/pdt/ProviderDefinedTypeTest.java
create mode 100644 gremlin-dotnet/src/Gremlin.Net/Driver/Remote/TransactionRemoteConnection.cs
create mode 100644 gremlin-dotnet/src/Gremlin.Net/Driver/RemoteTransaction.cs
delete mode 100644 gremlin-dotnet/src/Gremlin.Net/Process/Remote/RemoteTransaction.cs
delete mode 100644 gremlin-dotnet/src/Gremlin.Net/Process/Traversal/GraphSONVersion.cs
create mode 100644 gremlin-dotnet/src/Gremlin.Net/Structure/IO/GraphBinary4/Types/CompositePDTSerializer.cs
copy gremlin-dotnet/src/Gremlin.Net/{Process/Traversal/Strategy/Finalization/ReferenceElementStrategy.cs => Structure/IProviderDefinedTypeAdapter.cs} (56%)
create mode 100644 gremlin-dotnet/src/Gremlin.Net/Structure/ProviderDefinedAttribute.cs
create mode 100644 gremlin-dotnet/src/Gremlin.Net/Structure/ProviderDefinedType.cs
create mode 100644 gremlin-dotnet/src/Gremlin.Net/Structure/ProviderDefinedTypeRegistry.cs
create mode 100644 gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Driver/ClientBehaviorIntegrationTests.cs
copy gremlin-dotnet/{src/Gremlin.Net/Process/Traversal/ConnectedComponent.cs => test/Gremlin.Net.IntegrationTest/Driver/SocketServerConstants.cs} (50%)
create mode 100644 gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Driver/TransactionTests.cs
delete mode 100644 gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Process/Traversal/DriverRemoteConnection/GraphTraversalTransactionTests.cs
delete mode 100644 gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Util/SocketServerSettings.cs
delete mode 100644 gremlin-dotnet/test/Gremlin.Net.UnitTest/Process/Remote/RemoteTransactionTests.cs
create mode 100644 gremlin-dotnet/test/Gremlin.Net.UnitTest/Structure/IO/GraphBinary4/ProviderDefinedTypeTests.cs
create mode 100644 gremlin-dotnet/test/Gremlin.Net.UnitTest/Structure/ProviderDefinedAttributeTests.cs
create mode 100644 gremlin-dotnet/test/Gremlin.Net.UnitTest/Structure/ProviderDefinedTypeRegistryTests.cs
create mode 100644 gremlin-driver/src/main/java/org/apache/tinkerpop/gremlin/driver/exception/FailResponseException.java
delete mode 100644 gremlin-driver/src/main/java/org/apache/tinkerpop/gremlin/driver/interceptor/PayloadSerializingInterceptor.java
create mode 100644 gremlin-driver/src/test/java/org/apache/tinkerpop/gremlin/driver/ClientBehaviorIntegrateTest.java
delete mode 100644 gremlin-driver/src/test/java/org/apache/tinkerpop/gremlin/driver/ClusterConfigTest.java
delete mode 100644 gremlin-driver/src/test/java/org/apache/tinkerpop/gremlin/driver/ClusterTest.java
create mode 100644 gremlin-driver/src/test/java/org/apache/tinkerpop/gremlin/driver/InterceptorTest.java
create mode 100644 gremlin-driver/src/test/java/org/apache/tinkerpop/gremlin/driver/exception/FailResponseExceptionTest.java
create mode 100644 gremlin-go/driver/client_behavior_test.go
create mode 100644 gremlin-go/driver/pdtRegistry.go
create mode 100644 gremlin-go/driver/pdtRegistry_test.go
create mode 100644 gremlin-go/driver/providerDefinedType.go
copy gremlin-go/driver/{driverRemoteConnection_test.go => providerDefinedType_test.go} (72%)
copy gremlin-go/driver/{driverRemoteConnection_test.go => socket_server_constants_test.go} (59%)
create mode 100644 gremlin-go/driver/transaction.go
copy gremlin-go/driver/{marker.go => transactionRemoteConnection.go} (52%)
create mode 100644 gremlin-go/driver/transaction_test.go
create mode 100644 gremlin-groovy/src/test/groovy/org/apache/tinkerpop/gremlin/groovy/TreeSubscriptTest.groovy
create mode 100644 gremlin-js/gremlin-javascript/lib/driver/http-request.ts
create mode 100644 gremlin-js/gremlin-javascript/lib/structure/ProviderDefinedTypeRegistry.ts
copy gremlin-js/gremlin-javascript/lib/structure/io/binary/internals/{BinarySerializer.js => CompositePDTSerializer.js} (50%)
create mode 100644 gremlin-js/gremlin-javascript/test/integration/client-behavior-tests.js
create mode 100644 gremlin-js/gremlin-javascript/test/integration/match-tests.js
copy gremlin-js/{gremlin-mcp/src/gremlin/models/index.ts => gremlin-javascript/test/integration/socket-server-constants.js} (57%)
create mode 100644 gremlin-js/gremlin-javascript/test/integration/transaction-tests.js
create mode 100644 gremlin-js/gremlin-javascript/test/unit/connection-test.js
create mode 100644 gremlin-js/gremlin-javascript/test/unit/graphbinary/CompositePDTSerializer-test.js
create mode 100644 gremlin-js/gremlin-javascript/test/unit/http-request-test.js
create mode 100644 gremlin-js/gremlin-javascript/test/unit/match-test.js
create mode 100644 gremlin-js/gremlin-javascript/test/unit/pdt-registry-test.js
create mode 100644 gremlin-python/src/main/python/gremlin_python/driver/http_request.py
create mode 100644 gremlin-python/src/main/python/gremlin_python/driver/transaction.py
copy docker/gremlin-server/krb5.conf => gremlin-python/src/main/python/tests/integration/driver/socket_server_constants.py (62%)
create mode 100644 gremlin-python/src/main/python/tests/integration/driver/test_client_behavior.py
create mode 100644 gremlin-python/src/main/python/tests/integration/driver/test_transaction.py
delete mode 100644 gremlin-python/src/main/python/tests/integration/driver/test_web_socket_client_behavior.py
create mode 100644 gremlin-python/src/main/python/tests/unit/driver/test_interceptor.py
create mode 100644 gremlin-python/src/main/python/tests/unit/structure/io/test_provider_defined_type.py
create mode 100644 gremlin-server/src/main/java/org/apache/tinkerpop/gremlin/server/handler/HttpResponseCoordinator.java
rename gremlin-server/src/main/java/org/apache/tinkerpop/gremlin/server/{handler => transaction}/TransactionManager.java (93%)
rename gremlin-server/src/main/java/org/apache/tinkerpop/gremlin/server/{handler => transaction}/UnmanagedTransaction.java (78%)
delete mode 100644 gremlin-server/src/test/java/org/apache/tinkerpop/gremlin/driver/remote/GraphSONLangRemoteFeatureTest.java
delete mode 100644 gremlin-server/src/test/java/org/apache/tinkerpop/gremlin/driver/remote/GraphSONLangRemoteParameterizedFeatureTest.java
delete mode 100644 gremlin-server/src/test/java/org/apache/tinkerpop/gremlin/driver/remote/GraphSONRemoteComputerFeatureTest.java
create mode 100644 gremlin-server/src/test/java/org/apache/tinkerpop/gremlin/server/GremlinServerHttpPipeliningIntegrateTest.java
create mode 100644 gremlin-server/src/test/java/org/apache/tinkerpop/gremlin/server/handler/HttpGremlinEndpointHandlerTest.java
copy gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/PropertiesHolder.java => gremlin-server/src/test/java/org/apache/tinkerpop/gremlin/server/pdt/Address.java (66%)
copy gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/util/function/ConstantSupplier.java => gremlin-server/src/test/java/org/apache/tinkerpop/gremlin/server/pdt/Person.java (66%)
copy gremlin-core/src/test/java/org/apache/tinkerpop/gremlin/structure/io/graphson/GraphSONTokensTest.java => gremlin-server/src/test/java/org/apache/tinkerpop/gremlin/server/pdt/Point.java (68%)
copy data/air-routes.kryo => gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/structure/io/gryo/air-routes-v3.kryo (100%)
create mode 100644 gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/test/features/map/MatchString.feature
create mode 100644 gremlin-tools/gremlin-benchmark/src/main/java/org/apache/tinkerpop/gremlin/process/MatchStepBenchmark.java
delete mode 100644 gremlin-tools/gremlin-socket-server/conf/test-ws-gremlin.yaml
rename gremlin-tools/gremlin-socket-server/src/main/java/org/apache/tinkerpop/gremlin/socket/server/{SimpleSocketServer.java => SimpleTestServer.java} (90%)
create mode 100644 gremlin-tools/gremlin-socket-server/src/main/java/org/apache/tinkerpop/gremlin/socket/server/SocketServerConstants.java
delete mode 100644 gremlin-tools/gremlin-socket-server/src/main/java/org/apache/tinkerpop/gremlin/socket/server/SocketServerSettings.java
delete mode 100644 gremlin-tools/gremlin-socket-server/src/main/java/org/apache/tinkerpop/gremlin/socket/server/TestHandlers.java
create mode 100644 gremlin-tools/gremlin-socket-server/src/main/java/org/apache/tinkerpop/gremlin/socket/server/TestHttpGremlinHandler.java
copy gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/remote/traversal/RemoteTraverser.java => gremlin-tools/gremlin-socket-server/src/main/java/org/apache/tinkerpop/gremlin/socket/server/TestHttpServerInitializer.java (56%)
create mode 100644 gremlin-util/src/test/java/org/apache/tinkerpop/gremlin/util/ser/binary/GraphBinaryPdtSpiAutoWiringTest.java
create mode 100644 gremlin-util/src/test/java/org/apache/tinkerpop/gremlin/util/ser/binary/GraphBinaryWriterPdtTest.java
create mode 100644 gremlin-util/src/test/java/org/apache/tinkerpop/gremlin/util/ser/binary/TestPointAdapter.java
create mode 100644 gremlin-util/src/test/java/org/apache/tinkerpop/gremlin/util/ser/binary/types/ProviderDefinedTypeSerializerTest.java
delete mode 100644 gremlin-util/src/test/java/org/apache/tinkerpop/gremlin/util/ser/binary/types/sample/SamplePerson.java
delete mode 100644 gremlin-util/src/test/java/org/apache/tinkerpop/gremlin/util/ser/binary/types/sample/SamplePersonSerializer.java
delete mode 100644 gremlin-util/src/test/java/org/apache/tinkerpop/gremlin/util/ser/binary/types/sample/SamplePersonSerializerTest.java
create mode 100644 gremlin-util/src/test/resources/META-INF/services/org.apache.tinkerpop.gremlin.structure.io.pdt.ProviderDefinedTypeAdapter
create mode 100644 tinkergraph-gremlin/src/test/java/org/apache/tinkerpop/gremlin/gql/DefaultGqlExecutorTest.java
create mode 100644 tinkergraph-gremlin/src/test/java/org/apache/tinkerpop/gremlin/gql/DefaultGqlPlannerTest.java
create mode 100644 tinkergraph-gremlin/src/test/java/org/apache/tinkerpop/gremlin/tinkergraph/process/traversal/step/map/GqlMatchStepTest.java
create mode 100644 tinkergraph-gremlin/src/test/java/org/apache/tinkerpop/gremlin/tinkergraph/process/traversal/strategy/optimization/GqlDeclarativeMatchStrategyTest.java
delete mode 100644 tinkergraph-gremlin/src/test/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/MergeOnMatchLabelPatternsTest.java
create mode 100644 tinkubator/README.md
(tinkerpop) 03/05: Add GLV implementations for multi-label
Posted by xi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
xiazcy pushed a commit to branch multi-label-experiment
in repository https://gitbox.apache.org/repos/asf/tinkerpop.git
commit 0aa98968547b07c8c1f3b9565bb4c04277236ff4
Author: Yang Xia <xi...@gmail.com>
AuthorDate: Thu Jun 25 02:18:34 2026 -0700
Add GLV implementations for multi-label
Add multi-label support to all Gremlin Language Variants:
- .NET: GraphTraversal, GraphTraversalSource, Edge/Vertex structures, binary serializers
- Go: graphTraversal, graph structures, binary serializer/deserializer
- JavaScript: graph-traversal.ts, graph.ts, binary serializers
- Python: graph_traversal.py, graph.py, graphbinaryV4.py
- Update GLV test translations and Gherkin step bindings
- Add MergeEdge and AddEdge feature test scenarios for multi-label edges
---
.../Process/Traversal/GraphTraversal.cs | 94 +++++++++
.../Process/Traversal/GraphTraversalSource.cs | 34 ++++
.../src/Gremlin.Net/Process/Traversal/__.cs | 72 +++++++
gremlin-dotnet/src/Gremlin.Net/Structure/Edge.cs | 14 +-
.../IO/GraphBinary4/Types/EdgeSerializer.cs | 29 ++-
.../IO/GraphBinary4/Types/VertexSerializer.cs | 9 +-
gremlin-dotnet/src/Gremlin.Net/Structure/Vertex.cs | 13 +-
.../Gremlin.Net.IntegrationTest/Gherkin/Gremlin.cs | 26 +++
gremlin-go/driver/anonymousTraversal.go | 28 +++
gremlin-go/driver/cucumber/cucumberSteps_test.go | 1 -
gremlin-go/driver/cucumber/gremlin.go | 26 +++
gremlin-go/driver/graph.go | 6 +-
gremlin-go/driver/graphBinaryDeserializer.go | 15 +-
gremlin-go/driver/graphBinarySerializer.go | 32 ++-
gremlin-go/driver/graphTraversal.go | 24 +++
gremlin-go/driver/graph_test.go | 6 +-
.../lib/process/graph-traversal.ts | 44 +++++
.../gremlin-javascript/lib/structure/graph.ts | 30 ++-
.../io/binary/internals/EdgeSerializer.js | 49 +++--
.../io/binary/internals/GraphSerializer.js | 24 ++-
.../io/binary/internals/VertexSerializer.js | 16 +-
.../gremlin-javascript/test/cucumber/gremlin.js | 26 +++
gremlin-js/gremlin-mcp/src/translator/stepNames.ts | 8 +
.../gremlin_python/process/graph_traversal.py | 119 +++++++++++
.../main/python/gremlin_python/structure/graph.py | 26 ++-
.../gremlin_python/structure/io/graphbinaryV4.py | 55 ++++--
.../src/main/python/tests/feature/gremlin.py | 26 +++
.../gremlin/language/translator/translations.json | 217 +++++++++++++++++++++
.../gremlin/test/features/map/AddEdge.feature | 34 +++-
.../gremlin/test/features/map/MergeEdge.feature | 4 +-
.../test/features/sideEffect/AddLabel.feature | 16 ++
.../test/features/sideEffect/DropLabel.feature | 32 +++
.../ser/binary/TypeSerializerFailureTests.java | 2 +-
.../gremlin/tinkergraph/structure/TinkerEdge.java | 2 +-
.../tinkergraph/structure/TinkerVertex.java | 9 +-
35 files changed, 1080 insertions(+), 88 deletions(-)
diff --git a/gremlin-dotnet/src/Gremlin.Net/Process/Traversal/GraphTraversal.cs b/gremlin-dotnet/src/Gremlin.Net/Process/Traversal/GraphTraversal.cs
index 13447b6cf6..78393e3d9e 100644
--- a/gremlin-dotnet/src/Gremlin.Net/Process/Traversal/GraphTraversal.cs
+++ b/gremlin-dotnet/src/Gremlin.Net/Process/Traversal/GraphTraversal.cs
@@ -140,6 +140,21 @@ namespace Gremlin.Net.Process.Traversal
return Wrap<TStart, Edge>(this);
}
+ /// <summary>
+ /// Adds the addE step with multiple labels to this <see cref="GraphTraversal{SType, EType}" />.
+ /// </summary>
+ public GraphTraversal<TStart, Edge> AddE (string label1, string label2, params string[] moreLabels)
+ {
+ if (label1 == null) throw new ArgumentNullException(nameof(label1));
+ if (label2 == null) throw new ArgumentNullException(nameof(label2));
+ if (moreLabels == null) throw new ArgumentNullException(nameof(moreLabels));
+
+ var args = new List<object>(2 + moreLabels.Length) { label1, label2 };
+ args.AddRange(moreLabels);
+ GremlinLang.AddStep("addE", args.ToArray());
+ return Wrap<TStart, Edge>(this);
+ }
+
/// <summary>
/// Adds the addV step to this <see cref="GraphTraversal{SType, EType}" />.
/// </summary>
@@ -167,6 +182,21 @@ namespace Gremlin.Net.Process.Traversal
return Wrap<TStart, Vertex>(this);
}
+ /// <summary>
+ /// Adds the addV step with multiple labels to this <see cref="GraphTraversal{SType, EType}" />.
+ /// </summary>
+ public GraphTraversal<TStart, Vertex> AddV (string label1, string label2, params string[] moreLabels)
+ {
+ if (label1 == null) throw new ArgumentNullException(nameof(label1));
+ if (label2 == null) throw new ArgumentNullException(nameof(label2));
+ if (moreLabels == null) throw new ArgumentNullException(nameof(moreLabels));
+
+ var args = new List<object>(2 + moreLabels.Length) { label1, label2 };
+ args.AddRange(moreLabels);
+ GremlinLang.AddStep("addV", args.ToArray());
+ return Wrap<TStart, Vertex>(this);
+ }
+
/// <summary>
/// Adds the aggregate step to this <see cref="GraphTraversal{SType, EType}" />.
/// </summary>
@@ -1278,6 +1308,70 @@ namespace Gremlin.Net.Process.Traversal
GremlinLang.AddStep("label");
return Wrap<TStart, string>(this);
}
+
+ /// <summary>
+ /// Adds the labels step to this <see cref="GraphTraversal{SType, EType}" />.
+ /// </summary>
+ public GraphTraversal<TStart, string> Labels ()
+ {
+ GremlinLang.AddStep("labels");
+ return Wrap<TStart, string>(this);
+ }
+
+ /// <summary>
+ /// Adds the addLabel step to this <see cref="GraphTraversal{SType, EType}" />.
+ /// </summary>
+ public GraphTraversal<TStart, TEnd> AddLabel (string label, params string[] moreLabels)
+ {
+ if (label == null) throw new ArgumentNullException(nameof(label));
+ if (moreLabels == null) throw new ArgumentNullException(nameof(moreLabels));
+
+ var args = new List<object>(1 + moreLabels.Length) { label };
+ args.AddRange(moreLabels);
+ GremlinLang.AddStep("addLabel", args.ToArray());
+ return Wrap<TStart, TEnd>(this);
+ }
+
+ /// <summary>
+ /// Adds the addLabel step to this <see cref="GraphTraversal{SType, EType}" />.
+ /// </summary>
+ public GraphTraversal<TStart, TEnd> AddLabel (ITraversal labelTraversal)
+ {
+ GremlinLang.AddStep("addLabel", labelTraversal);
+ return Wrap<TStart, TEnd>(this);
+ }
+
+ /// <summary>
+ /// Adds the dropLabels step to this <see cref="GraphTraversal{SType, EType}" />.
+ /// </summary>
+ public GraphTraversal<TStart, TEnd> DropLabels ()
+ {
+ GremlinLang.AddStep("dropLabels");
+ return Wrap<TStart, TEnd>(this);
+ }
+
+ /// <summary>
+ /// Adds the dropLabel step to this <see cref="GraphTraversal{SType, EType}" />.
+ /// </summary>
+ public GraphTraversal<TStart, TEnd> DropLabel (string label, params string[] moreLabels)
+ {
+ if (label == null) throw new ArgumentNullException(nameof(label));
+ if (moreLabels == null) throw new ArgumentNullException(nameof(moreLabels));
+
+ var args = new List<object>(1 + moreLabels.Length) { label };
+ args.AddRange(moreLabels);
+ GremlinLang.AddStep("dropLabel", args.ToArray());
+ return Wrap<TStart, TEnd>(this);
+ }
+
+ /// <summary>
+ /// Adds the dropLabel step to this <see cref="GraphTraversal{SType, EType}" />.
+ /// </summary>
+ public GraphTraversal<TStart, TEnd> DropLabel (ITraversal labelTraversal)
+ {
+ GremlinLang.AddStep("dropLabel", labelTraversal);
+ return Wrap<TStart, TEnd>(this);
+ }
/// <summary>
/// Adds the length step to this <see cref="GraphTraversal{SType, EType}" />.
diff --git a/gremlin-dotnet/src/Gremlin.Net/Process/Traversal/GraphTraversalSource.cs b/gremlin-dotnet/src/Gremlin.Net/Process/Traversal/GraphTraversalSource.cs
index 947e5b1ec8..1501f558a8 100644
--- a/gremlin-dotnet/src/Gremlin.Net/Process/Traversal/GraphTraversalSource.cs
+++ b/gremlin-dotnet/src/Gremlin.Net/Process/Traversal/GraphTraversalSource.cs
@@ -356,6 +356,23 @@ namespace Gremlin.Net.Process.Traversal
return traversal;
}
+ /// <summary>
+ /// Spawns a <see cref="GraphTraversal{SType, EType}" /> off this graph traversal source and adds the addE step
+ /// with multiple labels to that traversal.
+ /// </summary>
+ public GraphTraversal<Edge, Edge> AddE(string label1, string label2, params string[] moreLabels)
+ {
+ if (label1 == null) throw new ArgumentNullException(nameof(label1));
+ if (label2 == null) throw new ArgumentNullException(nameof(label2));
+ if (moreLabels == null) throw new ArgumentNullException(nameof(moreLabels));
+
+ var traversal = new GraphTraversal<Edge, Edge>(TraversalStrategies, GremlinLang.Clone());
+ var args = new List<object>(2 + moreLabels.Length) { label1, label2 };
+ args.AddRange(moreLabels);
+ traversal.GremlinLang.AddStep("addE", args.ToArray());
+ return traversal;
+ }
+
/// <summary>
/// Spawns a <see cref="GraphTraversal{SType, EType}" /> off this graph traversal source and adds the mergeE step to that
/// traversal.
@@ -417,6 +434,23 @@ namespace Gremlin.Net.Process.Traversal
return traversal;
}
+ /// <summary>
+ /// Spawns a <see cref="GraphTraversal{SType, EType}" /> off this graph traversal source and adds the addV step
+ /// with multiple labels to that traversal.
+ /// </summary>
+ public GraphTraversal<Vertex, Vertex> AddV(string label1, string label2, params string[] moreLabels)
+ {
+ if (label1 == null) throw new ArgumentNullException(nameof(label1));
+ if (label2 == null) throw new ArgumentNullException(nameof(label2));
+ if (moreLabels == null) throw new ArgumentNullException(nameof(moreLabels));
+
+ var traversal = new GraphTraversal<Vertex, Vertex>(TraversalStrategies, GremlinLang.Clone());
+ var args = new List<object>(2 + moreLabels.Length) { label1, label2 };
+ args.AddRange(moreLabels);
+ traversal.GremlinLang.AddStep("addV", args.ToArray());
+ return traversal;
+ }
+
/// <summary>
/// Spawns a <see cref="GraphTraversal{SType, EType}" /> off this graph traversal source and adds the mergeV step to that
/// traversal.
diff --git a/gremlin-dotnet/src/Gremlin.Net/Process/Traversal/__.cs b/gremlin-dotnet/src/Gremlin.Net/Process/Traversal/__.cs
index 974521747f..1d21df4a32 100644
--- a/gremlin-dotnet/src/Gremlin.Net/Process/Traversal/__.cs
+++ b/gremlin-dotnet/src/Gremlin.Net/Process/Traversal/__.cs
@@ -76,6 +76,16 @@ namespace Gremlin.Net.Process.Traversal
return new GraphTraversal<object, Edge>().AddE(edgeLabelTraversal);
}
+ /// <summary>
+ /// Spawns a <see cref="GraphTraversal{SType, EType}" /> and adds the addE step with multiple labels to that traversal.
+ /// </summary>
+ public static GraphTraversal<object, Edge> AddE(string label1, string label2, params string[] moreLabels)
+ {
+ return moreLabels is { Length: 0 }
+ ? new GraphTraversal<object, Edge>().AddE(label1, label2)
+ : new GraphTraversal<object, Edge>().AddE(label1, label2, moreLabels);
+ }
+
/// <summary>
/// Spawns a <see cref="GraphTraversal{SType, EType}" /> and adds the addV step to that traversal.
/// </summary>
@@ -100,6 +110,16 @@ namespace Gremlin.Net.Process.Traversal
return new GraphTraversal<object, Vertex>().AddV(vertexLabelTraversal);
}
+ /// <summary>
+ /// Spawns a <see cref="GraphTraversal{SType, EType}" /> and adds the addV step with multiple labels to that traversal.
+ /// </summary>
+ public static GraphTraversal<object, Vertex> AddV(string label1, string label2, params string[] moreLabels)
+ {
+ return moreLabels is { Length: 0 }
+ ? new GraphTraversal<object, Vertex>().AddV(label1, label2)
+ : new GraphTraversal<object, Vertex>().AddV(label1, label2, moreLabels);
+ }
+
/// <summary>
/// Spawns a <see cref="GraphTraversal{SType, EType}" /> and adds the aggregate step to that traversal.
/// </summary>
@@ -893,6 +913,58 @@ namespace Gremlin.Net.Process.Traversal
{
return new GraphTraversal<object, string>().Label();
}
+
+ /// <summary>
+ /// Spawns a <see cref="GraphTraversal{SType, EType}" /> and adds the labels step to that traversal.
+ /// </summary>
+ public static GraphTraversal<object, string> Labels()
+ {
+ return new GraphTraversal<object, string>().Labels();
+ }
+
+ /// <summary>
+ /// Spawns a <see cref="GraphTraversal{SType, EType}" /> and adds the addLabel step to that traversal.
+ /// </summary>
+ public static GraphTraversal<object, object> AddLabel(string label, params string[] moreLabels)
+ {
+ return moreLabels is { Length: 0 }
+ ? new GraphTraversal<object, object>().AddLabel(label)
+ : new GraphTraversal<object, object>().AddLabel(label, moreLabels);
+ }
+
+ /// <summary>
+ /// Spawns a <see cref="GraphTraversal{SType, EType}" /> and adds the addLabel step to that traversal.
+ /// </summary>
+ public static GraphTraversal<object, object> AddLabel(ITraversal labelTraversal)
+ {
+ return new GraphTraversal<object, object>().AddLabel(labelTraversal);
+ }
+
+ /// <summary>
+ /// Spawns a <see cref="GraphTraversal{SType, EType}" /> and adds the dropLabels step to that traversal.
+ /// </summary>
+ public static GraphTraversal<object, object> DropLabels()
+ {
+ return new GraphTraversal<object, object>().DropLabels();
+ }
+
+ /// <summary>
+ /// Spawns a <see cref="GraphTraversal{SType, EType}" /> and adds the dropLabel step to that traversal.
+ /// </summary>
+ public static GraphTraversal<object, object> DropLabel(string label, params string[] moreLabels)
+ {
+ return moreLabels is { Length: 0 }
+ ? new GraphTraversal<object, object>().DropLabel(label)
+ : new GraphTraversal<object, object>().DropLabel(label, moreLabels);
+ }
+
+ /// <summary>
+ /// Spawns a <see cref="GraphTraversal{SType, EType}" /> and adds the dropLabel step to that traversal.
+ /// </summary>
+ public static GraphTraversal<object, object> DropLabel(ITraversal labelTraversal)
+ {
+ return new GraphTraversal<object, object>().DropLabel(labelTraversal);
+ }
/// <summary>
/// Spawns a <see cref="GraphTraversal{SType, EType}" /> and adds the length step to that traversal.
diff --git a/gremlin-dotnet/src/Gremlin.Net/Structure/Edge.cs b/gremlin-dotnet/src/Gremlin.Net/Structure/Edge.cs
index 63461fa4b2..d0e2cc01db 100644
--- a/gremlin-dotnet/src/Gremlin.Net/Structure/Edge.cs
+++ b/gremlin-dotnet/src/Gremlin.Net/Structure/Edge.cs
@@ -21,6 +21,8 @@
#endregion
+using System.Collections.Generic;
+using System.Collections.Immutable;
using System.Linq;
namespace Gremlin.Net.Structure
@@ -38,13 +40,23 @@ namespace Gremlin.Net.Structure
/// <param name="label">The label of the edge.</param>
/// <param name="inV">The incoming/head vertex of the edge.</param>
/// <param name="properties">Optional properties of the edge.</param>
- public Edge(object? id, Vertex outV, string label, Vertex inV, dynamic[]? properties = null)
+ /// <param name="labels">Optional set of labels for multi-label support.</param>
+ public Edge(object? id, Vertex outV, string label, Vertex inV, dynamic[]? properties = null,
+ IEnumerable<string>? labels = null)
: base(id, label, properties)
{
OutV = outV;
InV = inV;
+ Labels = labels != null
+ ? ImmutableHashSet.CreateRange(labels)
+ : ImmutableHashSet.Create(label ?? "edge");
}
+ /// <summary>
+ /// Gets all labels on this edge.
+ /// </summary>
+ public IReadOnlySet<string> Labels { get; }
+
/// <summary>
/// Gets the incoming/head vertex of this edge.
/// </summary>
diff --git a/gremlin-dotnet/src/Gremlin.Net/Structure/IO/GraphBinary4/Types/EdgeSerializer.cs b/gremlin-dotnet/src/Gremlin.Net/Structure/IO/GraphBinary4/Types/EdgeSerializer.cs
index b3a8097de5..483d4b3fd8 100644
--- a/gremlin-dotnet/src/Gremlin.Net/Structure/IO/GraphBinary4/Types/EdgeSerializer.cs
+++ b/gremlin-dotnet/src/Gremlin.Net/Structure/IO/GraphBinary4/Types/EdgeSerializer.cs
@@ -47,12 +47,12 @@ namespace Gremlin.Net.Structure.IO.GraphBinary4.Types
CancellationToken cancellationToken = default)
{
await writer.WriteAsync(value.Id, stream, cancellationToken).ConfigureAwait(false);
- await writer.WriteNonNullableValueAsync(new List<string> { value.Label }, stream, cancellationToken).ConfigureAwait(false);
+ await writer.WriteNonNullableValueAsync(new List<string>(value.Labels), stream, cancellationToken).ConfigureAwait(false);
await writer.WriteAsync(value.InV.Id, stream, cancellationToken).ConfigureAwait(false);
- await writer.WriteNonNullableValueAsync(new List<string> { value.InV.Label }, stream, cancellationToken).ConfigureAwait(false);
+ await writer.WriteNonNullableValueAsync(new List<string>(value.InV.Labels), stream, cancellationToken).ConfigureAwait(false);
await writer.WriteAsync(value.OutV.Id, stream, cancellationToken).ConfigureAwait(false);
- await writer.WriteNonNullableValueAsync(new List<string> { value.OutV.Label }, stream, cancellationToken).ConfigureAwait(false);
+ await writer.WriteNonNullableValueAsync(new List<string>(value.OutV.Labels), stream, cancellationToken).ConfigureAwait(false);
// Placeholder for the parent vertex
await writer.WriteAsync(null, stream, cancellationToken).ConfigureAwait(false);
@@ -68,14 +68,31 @@ namespace Gremlin.Net.Structure.IO.GraphBinary4.Types
var id = await reader.ReadAsync(stream, cancellationToken).ConfigureAwait(false);
var labelList = (List<string?>)await reader.ReadNonNullableValueAsync<List<string?>>(stream, cancellationToken).ConfigureAwait(false);
var label = labelList.Count > 0 ? labelList[0] ?? "" : "";
+ var labels = new List<string>();
+ foreach (var l in labelList)
+ {
+ if (l != null) labels.Add(l);
+ }
var inVId = await reader.ReadAsync(stream, cancellationToken).ConfigureAwait(false);
var inVLabelList = (List<string?>)await reader.ReadNonNullableValueAsync<List<string?>>(stream, cancellationToken).ConfigureAwait(false);
- var inV = new Vertex(inVId, inVLabelList.Count > 0 ? inVLabelList[0] ?? "" : "");
+ var inVLabel = inVLabelList.Count > 0 ? inVLabelList[0] ?? "" : "";
+ var inVLabels = new List<string>();
+ foreach (var l in inVLabelList)
+ {
+ if (l != null) inVLabels.Add(l);
+ }
+ var inV = new Vertex(inVId, inVLabel, labels: inVLabels);
var outVId = await reader.ReadAsync(stream, cancellationToken).ConfigureAwait(false);
var outVLabelList = (List<string?>)await reader.ReadNonNullableValueAsync<List<string?>>(stream, cancellationToken).ConfigureAwait(false);
- var outV = new Vertex(outVId, outVLabelList.Count > 0 ? outVLabelList[0] ?? "" : "");
+ var outVLabel = outVLabelList.Count > 0 ? outVLabelList[0] ?? "" : "";
+ var outVLabels = new List<string>();
+ foreach (var l in outVLabelList)
+ {
+ if (l != null) outVLabels.Add(l);
+ }
+ var outV = new Vertex(outVId, outVLabel, labels: outVLabels);
// discard possible parent vertex
await reader.ReadAsync(stream, cancellationToken).ConfigureAwait(false);
@@ -83,7 +100,7 @@ namespace Gremlin.Net.Structure.IO.GraphBinary4.Types
var properties = await reader.ReadAsync(stream, cancellationToken).ConfigureAwait(false);
var propertiesAsArray = null == properties ? Array.Empty<object>() : (properties as List<object>)?.ToArray();
- return new Edge(id, outV, label, inV, propertiesAsArray);
+ return new Edge(id, outV, label, inV, propertiesAsArray, labels);
}
}
}
diff --git a/gremlin-dotnet/src/Gremlin.Net/Structure/IO/GraphBinary4/Types/VertexSerializer.cs b/gremlin-dotnet/src/Gremlin.Net/Structure/IO/GraphBinary4/Types/VertexSerializer.cs
index 9bad7be2d7..2c3e1c2d5e 100644
--- a/gremlin-dotnet/src/Gremlin.Net/Structure/IO/GraphBinary4/Types/VertexSerializer.cs
+++ b/gremlin-dotnet/src/Gremlin.Net/Structure/IO/GraphBinary4/Types/VertexSerializer.cs
@@ -47,7 +47,7 @@ namespace Gremlin.Net.Structure.IO.GraphBinary4.Types
CancellationToken cancellationToken = default)
{
await writer.WriteAsync(value.Id, stream, cancellationToken).ConfigureAwait(false);
- await writer.WriteNonNullableValueAsync(new List<string> { value.Label }, stream, cancellationToken).ConfigureAwait(false);
+ await writer.WriteNonNullableValueAsync(new List<string>(value.Labels), stream, cancellationToken).ConfigureAwait(false);
await writer.WriteAsync(null, stream, cancellationToken).ConfigureAwait(false); // properties
}
@@ -58,11 +58,16 @@ namespace Gremlin.Net.Structure.IO.GraphBinary4.Types
var id = await reader.ReadAsync(stream, cancellationToken).ConfigureAwait(false);
var labelList = (List<string?>)await reader.ReadNonNullableValueAsync<List<string?>>(stream, cancellationToken).ConfigureAwait(false);
var label = labelList.Count > 0 ? labelList[0] ?? "" : "";
+ var labels = new List<string>();
+ foreach (var l in labelList)
+ {
+ if (l != null) labels.Add(l);
+ }
var properties = await reader.ReadAsync(stream, cancellationToken).ConfigureAwait(false);
var propertiesAsArray = null == properties ? Array.Empty<object>() : (properties as List<object>)?.ToArray();
- return new Vertex(id, label, propertiesAsArray);
+ return new Vertex(id, label, propertiesAsArray, labels);
}
}
}
diff --git a/gremlin-dotnet/src/Gremlin.Net/Structure/Vertex.cs b/gremlin-dotnet/src/Gremlin.Net/Structure/Vertex.cs
index 6f56102ac0..036efd46e4 100644
--- a/gremlin-dotnet/src/Gremlin.Net/Structure/Vertex.cs
+++ b/gremlin-dotnet/src/Gremlin.Net/Structure/Vertex.cs
@@ -22,6 +22,7 @@
#endregion
using System.Collections.Generic;
+using System.Collections.Immutable;
using System.Linq;
namespace Gremlin.Net.Structure
@@ -42,11 +43,21 @@ namespace Gremlin.Net.Structure
/// <param name="id">The id of the vertex.</param>
/// <param name="label">The label of the vertex.</param>
/// <param name="properties">Optional properties of the vertex.</param>
- public Vertex(object? id, string label = DefaultLabel, dynamic[]? properties = null)
+ /// <param name="labels">Optional set of labels for multi-label support.</param>
+ public Vertex(object? id, string label = DefaultLabel, dynamic[]? properties = null,
+ IEnumerable<string>? labels = null)
: base(id, label, properties)
{
+ Labels = labels != null
+ ? ImmutableHashSet.CreateRange(labels)
+ : ImmutableHashSet.Create(label ?? DefaultLabel);
}
+ /// <summary>
+ /// Gets all labels on this vertex.
+ /// </summary>
+ public IReadOnlySet<string> Labels { get; }
+
/// <summary>
/// Get property by key
/// </summary>
diff --git a/gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Gherkin/Gremlin.cs b/gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Gherkin/Gremlin.cs
index 315b5fb70a..5728b738ba 100644
--- a/gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Gherkin/Gremlin.cs
+++ b/gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Gherkin/Gremlin.cs
@@ -956,6 +956,8 @@ namespace Gremlin.Net.IntegrationTest.Gherkin
{"g_V_limitX3X_addVXsoftwareX_aggregateXa1X_byXlabelX_aggregateXa2X_byXlabelX_capXa1_a2X_selectXa_bX_byXunfoldX_foldX", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.AddV((string) "person").Property("name", "marko").Property("age", 29).As("marko").AddV((string) "person").Property("name", "vadas").Property("age", 27).As("vadas").AddV((string) "software").Property("name", "lop").Property("lang", "java").As("lop").AddV((string) "pers [...]
{"g_addV_propertyXname_markoX_withXkey_valueX_valuesXname_keyX", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.AddV().Property("name", "marko").With("key", "value").Values<object>("name", "key")}},
{"g_addV_propertyXname_marko_since_2010X_withXkey_valueX_propertiesXnameX_valuesXsince_keyX", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.AddV().Property("name", "marko", "since", 2010).With("key", "value").Properties<object>("name").Values<object>("since", "key")}},
+ {"g_addVXa_bX_labels", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.AddV((string) "a", (string) "b").Labels().Fold(), (g,p) =>g.V().HasLabel("a").HasLabel("b"), (g,p) =>g.AddV((string) "a", (string) "b"), (g,p) =>g.V().Labels()}},
+ {"g_addVXa_b_cX_labels_count", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.AddV((string) "a", (string) "b", (string) "c").Labels().Count()}},
{"g_injectX1X_asBool", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.Inject<object>(1).AsBool()}},
{"g_injectX3_14X_asBool", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.Inject<object>(3.14).AsBool()}},
{"g_injectXneg_1X_asBool", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.Inject<object>(-1).AsBool()}},
@@ -1250,6 +1252,10 @@ namespace Gremlin.Net.IntegrationTest.Gherkin
{"g_injectXListX1_2XX_lTrimXlocalX", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.Inject<object>(new List<object> { 1, 2 }).LTrim<object>(Scope.Local)}},
{"g_V_valuesXnameX_lTrim", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.AddV((string) "person").Property("name", " marko ").Property("age", 29).As("marko").AddV((string) "person").Property("name", " vadas ").Property("age", 27).As("vadas").AddV((string) "software").Property("name", " lop").Property("lang", "java").As("lop").AddV((string) "person").Property("name", "josh ").Property("age", 32).As("josh").AddV((string) "softwar [...]
{"g_V_valuesXnameX_order_fold_lTrimXlocalX", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.AddV((string) "person").Property("name", " marko ").Property("age", 29).As("marko").AddV((string) "person").Property("name", " vadas ").Property("age", 27).As("vadas").AddV((string) "software").Property("name", " lop").Property("lang", "java").As("lop").AddV((string) "person").Property("name", "josh ").Property("age", 32).As("josh").AddV [...]
+ {"g_V_hasLabelXpersonX_labels", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.V().HasLabel("person").Labels()}},
+ {"g_addVXa_bX_labels_count", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.AddV((string) "a", (string) "b"), (g,p) =>g.V().Labels().Count()}},
+ {"g_addV_labels", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.AddV(), (g,p) =>g.V().Labels()}},
+ {"g_E_labels", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.E().HasLabel("knows").Labels()}},
{"g_injectXfeature_test_nullX_length", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.Inject<object>("feature", "test", null).Length()}},
{"g_injectXfeature_test_nullX_lengthXlocalX", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.Inject<object>("feature", "test", null).Length<object>(Scope.Local)}},
{"g_injectXListXa_bXX_length", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.Inject<object>(new List<object> { "a", "b" }).Length()}},
@@ -1516,6 +1522,15 @@ namespace Gremlin.Net.IntegrationTest.Gherkin
{"g_mergeV_hidden_label_key_onMatch_matched_prohibited", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.MergeV((IDictionary<object, object>) new Dictionary<object, object> {}).Option(Merge.OnMatch, (IDictionary<object, object>) p["xx1"])}},
{"g_injectXlist1_list2_list3X_fold_asXmX_mergeVXselectXmX_limitXlocal_1X_unfoldX_optionXonCreate_selectXmX_rangeXlocal_1_2X_unfoldX_optionXonMatch_selectXmX_tailXlocalX_unfoldX_to_match", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.AddV((string) "person").Property("name", "marko").Property("age", 29), (g,p) =>g.Inject<object>(new Dictionary<object, object> {{ T.Label, "person" }, { "name", "marko" }}, new Dictionary<object, obje [...]
{"g_injectXlist1_list2_list3X_fold_asXmX_mergeVXselectXmX_limitXlocal_1X_unfoldX_optionXonCreate_selectXmX_rangeXlocal_1_2X_unfoldX_optionXonMatch_selectXmX_tailXlocalX_unfoldX_to_create", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.AddV((string) "person").Property("name", "marko").Property("age", 29), (g,p) =>g.Inject<object>(new Dictionary<object, object> {{ T.Label, "person" }, { "name", "stephen" }}, new Dictionary<object, o [...]
+ {"g_mergeVXlabel_ab_name_markoX_multilabel_create", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.MergeV((IDictionary<object, object>) new Dictionary<object, object> {{ T.Label, new List<object> { "person", "employee" } }, { "name", "marko" }}), (g,p) =>g.V(), (g,p) =>g.V().HasLabel("person").HasLabel("employee"), (g,p) =>g.V().Has("name", "marko")}},
+ {"g_mergeVXlabel_abc_name_testX_multilabel_create", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.MergeV((IDictionary<object, object>) new Dictionary<object, object> {{ T.Label, new List<object> { "a", "b", "c" } }, { "name", "test" }}), (g,p) =>g.V(), (g,p) =>g.V().HasLabel("a").HasLabel("b").HasLabel("c")}},
+ {"g_mergeVXlabel_ab_name_markoX_multilabel_match", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.AddV((string) "person").AddLabel("employee").Property("name", "marko"), (g,p) =>g.MergeV((IDictionary<object, object>) new Dictionary<object, object> {{ T.Label, new List<object> { "person", "employee" } }, { "name", "marko" }}), (g,p) =>g.V(), (g,p) =>g.V().HasLabel("person").HasLabel("employee")}},
+ {"g_mergeVXlabel_ab_name_markoX_multilabel_nomatch", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.AddV((string) "person").Property("name", "marko"), (g,p) =>g.MergeV((IDictionary<object, object>) new Dictionary<object, object> {{ T.Label, new List<object> { "person", "employee" } }, { "name", "marko" }}), (g,p) =>g.V()}},
+ {"g_mergeVXlabel_person_name_markoX_optionXonMatch_label_managerX", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.AddV((string) "person").AddLabel("employee").Property("name", "marko"), (g,p) =>g.MergeV((IDictionary<object, object>) new Dictionary<object, object> {{ T.Label, "person" }, { "name", "marko" }}).Option(Merge.OnMatch, (IDictionary<object, object>) new Dictionary<object, object> {{ T.Label, "manager" }}), (g,p) =>g.V(), [...]
+ {"g_mergeVXlabel_person_name_markoX_optionXonMatch_label_manager_directorX", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.AddV((string) "person").Property("name", "marko"), (g,p) =>g.MergeV((IDictionary<object, object>) new Dictionary<object, object> {{ T.Label, "person" }, { "name", "marko" }}).Option(Merge.OnMatch, (IDictionary<object, object>) new Dictionary<object, object> {{ T.Label, new List<object> { "manager", "director" [...]
+ {"g_mergeVXlabel_person_name_markoX_optionXonMatch_label_emptyX", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.AddV((string) "person").Property("name", "marko"), (g,p) =>g.MergeV((IDictionary<object, object>) new Dictionary<object, object> {{ T.Label, "person" }, { "name", "marko" }}).Option(Merge.OnMatch, (IDictionary<object, object>) new Dictionary<object, object> {{ T.Label, new List<object> { } }}), (g,p) =>g.V(), (g,p) =>g. [...]
+ {"g_mergeVXname_markoX_optionXonCreate_label_ab_name_markoX", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.MergeV((IDictionary<object, object>) new Dictionary<object, object> {{ "name", "marko" }}).Option(Merge.OnCreate, (IDictionary<object, object>) new Dictionary<object, object> {{ T.Label, new List<object> { "person", "employee" } }, { "name", "marko" }}), (g,p) =>g.V(), (g,p) =>g.V().HasLabel("person").HasLabel("employee"), ( [...]
+ {"g_mergeVXlabel_person_name_markoX_optionXonMatch_label_existingX", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.AddV((string) "person").AddLabel("employee").Property("name", "marko"), (g,p) =>g.MergeV((IDictionary<object, object>) new Dictionary<object, object> {{ T.Label, "person" }, { "name", "marko" }}).Option(Merge.OnMatch, (IDictionary<object, object>) new Dictionary<object, object> {{ T.Label, "person" }}), (g,p) =>g.V(), [...]
{"g_V_age_min", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.V().Values<object>("age").Min<object>()}},
{"g_V_foo_min", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.V().Values<object>("foo").Min<object>()}},
{"g_V_name_min", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.V().Values<object>("name").Min<object>()}},
@@ -2001,6 +2016,10 @@ namespace Gremlin.Net.IntegrationTest.Gherkin
{"g_V_out_out_properties_asXheadX_path_order_byXdescX_selectXheadX_value", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.V().Out().Out().Properties<object>().As("head").Path().Order().By(Order.Desc).Select<object>("head").Value<object>()}},
{"g_V_out_out_values_asXheadX_path_order_byXascX_selectXheadX", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.V().Out().Out().Values<object>().As("head").Path().Order().By(Order.Asc).Select<object>("head")}},
{"g_V_out_out_values_asXheadX_path_order_byXdescX_selectXheadX", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.V().Out().Out().Values<object>().As("head").Path().Order().By(Order.Desc).Select<object>("head")}},
+ {"g_V_hasLabelXpersonX_hasXname_markoX_addLabelXemployeeX_labels", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.AddV((string) "person").Property("name", "marko"), (g,p) =>g.V().HasLabel("person").Has("name", "marko").AddLabel("employee").Labels().Fold(), (g,p) =>g.V().HasLabel("person").HasLabel("employee")}},
+ {"g_V_addLabelXa_bX_labels_count", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.AddV((string) "person"), (g,p) =>g.V().AddLabel("a", "b").Labels().Count()}},
+ {"g_V_addLabelXexistingX_labels_count", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.AddV((string) "person"), (g,p) =>g.V().AddLabel("person").Labels().Count()}},
+ {"g_E_addLabelXfriendX_labels_fold", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.AddV((string) "person").Property("name", "marko").As("a").AddV((string) "person").Property("name", "josh").As("b").AddE((string) "knows").From("a").To("b"), (g,p) =>g.E().AddLabel("friend").Labels().Fold()}},
{"g_V_valueXnameX_aggregateXxX_capXxX", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.V().Values<object>("name").Aggregate("x").Cap<object>("x")}},
{"g_V_aggregateXxX_byXnameX_capXxX", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.V().Aggregate("x").By("name").Cap<object>("x")}},
{"g_V_out_aggregateXaX_path", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.V().Out().Aggregate("a").Path()}},
@@ -2058,6 +2077,13 @@ namespace Gremlin.Net.IntegrationTest.Gherkin
{"g_V_repeatXaggregateXaXX_timesX2X_capXaX_unfold", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.V().Repeat(__.Aggregate("a")).Times(2).Cap<object>("a").Unfold<object>()}},
{"g_V_aggregateXaX_capXaX_unfold_both", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.V().Aggregate("a").Cap<object>("a").Unfold<object>().Both()}},
{"g_V_aggregateXaX_capXaX_unfold_barrier_both", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.V().Aggregate("a").Cap<object>("a").Unfold<object>().Barrier().Both()}},
+ {"g_V_dropLabelXaX_labels", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.AddV((string) "a", (string) "b"), (g,p) =>g.V().DropLabel("a").Labels().Fold(), (g,p) =>g.V().HasLabel("a"), (g,p) =>g.V().HasLabel("b")}},
+ {"g_V_dropLabels_labels", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.AddV((string) "a", (string) "b"), (g,p) =>g.V().DropLabels().Labels()}},
+ {"g_V_dropLabelXa_bX_labels", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.AddV((string) "a", (string) "b", (string) "c"), (g,p) =>g.V().DropLabel("a", "b").Labels()}},
+ {"g_V_dropLabels_defaultLabel", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.AddV((string) "person"), (g,p) =>g.V().DropLabels().Labels()}},
+ {"g_E_dropLabelXknowsX_labels", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.AddV((string) "person").As("a").AddV((string) "person").As("b").AddE((string) "knows").From("a").To("b"), (g,p) =>g.E().DropLabel("knows").Labels().Fold()}},
+ {"g_E_dropLabels_labels", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.AddV((string) "person").As("a").AddV((string) "person").As("b").AddE((string) "knows").From("a").To("b"), (g,p) =>g.E().DropLabels().Labels()}},
+ {"g_V_dropLabelXnonExistentX_labels", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.AddV((string) "a", (string) "b"), (g,p) =>g.V().DropLabel("xyz").Labels()}},
{"g_V_fail", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.V().Fail()}},
{"g_V_failXmsgX", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.V().Fail("msg")}},
{"g_V_unionXout_failX", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.V().Union<object>(__.Out(), __.Fail())}},
diff --git a/gremlin-go/driver/anonymousTraversal.go b/gremlin-go/driver/anonymousTraversal.go
index 8a16eb91b8..8eb7c90db6 100644
--- a/gremlin-go/driver/anonymousTraversal.go
+++ b/gremlin-go/driver/anonymousTraversal.go
@@ -63,6 +63,8 @@ type AnonymousTraversal interface {
V(args ...interface{}) *GraphTraversal
// AddE adds the addE step to the GraphTraversal.
AddE(args ...interface{}) *GraphTraversal
+ // AddLabel adds the addLabel step to the GraphTraversal.
+ AddLabel(args ...interface{}) *GraphTraversal
// AddV adds the addV step to the GraphTraversal.
AddV(args ...interface{}) *GraphTraversal
// Aggregate adds the aggregate step to the GraphTraversal.
@@ -133,6 +135,10 @@ type AnonymousTraversal interface {
Disjunct(args ...interface{}) *GraphTraversal
// Drop adds the drop step to the GraphTraversal.
Drop(args ...interface{}) *GraphTraversal
+ // DropLabel adds the dropLabel step to the GraphTraversal.
+ DropLabel(args ...interface{}) *GraphTraversal
+ // DropLabels adds the dropLabels step to the GraphTraversal.
+ DropLabels(args ...interface{}) *GraphTraversal
// Element adds the element step to the GraphTraversal.
Element(args ...interface{}) *GraphTraversal
// ElementMap adds the elementMap step to the GraphTraversal.
@@ -189,6 +195,8 @@ type AnonymousTraversal interface {
Key(args ...interface{}) *GraphTraversal
// Label adds the label step to the GraphTraversal.
Label(args ...interface{}) *GraphTraversal
+ // Labels adds the labels step to the GraphTraversal.
+ Labels(args ...interface{}) *GraphTraversal
// Length adds the length step to the GraphTraversal.
Length(args ...interface{}) *GraphTraversal
// Limit adds the limit step to the GraphTraversal.
@@ -361,6 +369,11 @@ func (anonymousTraversal *anonymousTraversal) AddE(args ...interface{}) *GraphTr
return anonymousTraversal.graphTraversal().AddE(args...)
}
+// AddLabel adds the addLabel step to the GraphTraversal.
+func (anonymousTraversal *anonymousTraversal) AddLabel(args ...interface{}) *GraphTraversal {
+ return anonymousTraversal.graphTraversal().AddLabel(args...)
+}
+
// AddV adds the addV step to the GraphTraversal.
func (anonymousTraversal *anonymousTraversal) AddV(args ...interface{}) *GraphTraversal {
return anonymousTraversal.graphTraversal().AddV(args...)
@@ -536,6 +549,16 @@ func (anonymousTraversal *anonymousTraversal) Drop(args ...interface{}) *GraphTr
return anonymousTraversal.graphTraversal().Drop(args...)
}
+// DropLabel adds the dropLabel step to the GraphTraversal.
+func (anonymousTraversal *anonymousTraversal) DropLabel(args ...interface{}) *GraphTraversal {
+ return anonymousTraversal.graphTraversal().DropLabel(args...)
+}
+
+// DropLabels adds the dropLabels step to the GraphTraversal.
+func (anonymousTraversal *anonymousTraversal) DropLabels(args ...interface{}) *GraphTraversal {
+ return anonymousTraversal.graphTraversal().DropLabels(args...)
+}
+
// Element adds the element step to the GraphTraversal.
func (anonymousTraversal *anonymousTraversal) Element(args ...interface{}) *GraphTraversal {
return anonymousTraversal.graphTraversal().Element(args...)
@@ -676,6 +699,11 @@ func (anonymousTraversal *anonymousTraversal) Label(args ...interface{}) *GraphT
return anonymousTraversal.graphTraversal().Label(args...)
}
+// Labels adds the labels step to the GraphTraversal.
+func (anonymousTraversal *anonymousTraversal) Labels(args ...interface{}) *GraphTraversal {
+ return anonymousTraversal.graphTraversal().Labels(args...)
+}
+
// Length adds the length step to the GraphTraversal.
func (anonymousTraversal *anonymousTraversal) Length(args ...interface{}) *GraphTraversal {
return anonymousTraversal.graphTraversal().Length(args...)
diff --git a/gremlin-go/driver/cucumber/cucumberSteps_test.go b/gremlin-go/driver/cucumber/cucumberSteps_test.go
index fd69c063d0..6cbf768215 100644
--- a/gremlin-go/driver/cucumber/cucumberSteps_test.go
+++ b/gremlin-go/driver/cucumber/cucumberSteps_test.go
@@ -1129,7 +1129,6 @@ func TestCucumberFeatures(t *testing.T) {
TestSuiteInitializer: InitializeTestSuite,
ScenarioInitializer: InitializeScenario,
Options: &godog.Options{
- Tags: "~@GraphComputerOnly && ~@AllowNullPropertyValues && ~@StepTree && ~@StepWrite && ~@DataChar",
Tags: "~@GraphComputerOnly && ~@AllowNullPropertyValues && ~@StepTree && ~@StepWrite && ~@DataChar && ~@MultiLabel",
Format: "pretty",
Paths: []string{getEnvOrDefaultString("CUCUMBER_FEATURE_FOLDER", "../../../gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/test/features")},
diff --git a/gremlin-go/driver/cucumber/gremlin.go b/gremlin-go/driver/cucumber/gremlin.go
index 343500fa13..a688116d6f 100644
--- a/gremlin-go/driver/cucumber/gremlin.go
+++ b/gremlin-go/driver/cucumber/gremlin.go
@@ -926,6 +926,8 @@ var translationMap = map[string][]func(g *gremlingo.GraphTraversalSource, p map[
"g_V_limitX3X_addVXsoftwareX_aggregateXa1X_byXlabelX_aggregateXa2X_byXlabelX_capXa1_a2X_selectXa_bX_byXunfoldX_foldX": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.AddV("person").Property("name", "marko").Property("age", 29).As("marko").AddV("person").Property("name", "vadas").Property("age", 27).As("vadas").AddV("software").Property("name", "lop").Property("lang", "java").As("lop").AddV("person").Property("name", "josh").Prop [...]
"g_addV_propertyXname_markoX_withXkey_valueX_valuesXname_keyX": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.AddV().Property("name", "marko").With("key", "value").Values("name", "key")}},
"g_addV_propertyXname_marko_since_2010X_withXkey_valueX_propertiesXnameX_valuesXsince_keyX": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.AddV().Property("name", "marko", "since", 2010).With("key", "value").Properties("name").Values("since", "key")}},
+ "g_addVXa_bX_labels": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.AddV("a", "b").Labels().Fold()}, func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.V().HasLabel("a").HasLabel("b")}, func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.AddV("a", "b")}, func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremling [...]
+ "g_addVXa_b_cX_labels_count": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.AddV("a", "b", "c").Labels().Count()}},
"g_injectX1X_asBool": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.Inject(1).AsBool()}},
"g_injectX3_14X_asBool": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.Inject(3.14).AsBool()}},
"g_injectXneg_1X_asBool": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.Inject(-1).AsBool()}},
@@ -1220,6 +1222,10 @@ var translationMap = map[string][]func(g *gremlingo.GraphTraversalSource, p map[
"g_injectXListX1_2XX_lTrimXlocalX": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.Inject([]interface{}{1, 2}).LTrim(gremlingo.Scope.Local)}},
"g_V_valuesXnameX_lTrim": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.AddV("person").Property("name", " marko ").Property("age", 29).As("marko").AddV("person").Property("name", " vadas ").Property("age", 27).As("vadas").AddV("software").Property("name", " lop").Property("lang", "java").As("lop").AddV("person").Property("name", "josh ").Property("age", 32).As("josh").AddV("software").Property("name", " ripple ").Proper [...]
"g_V_valuesXnameX_order_fold_lTrimXlocalX": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.AddV("person").Property("name", " marko ").Property("age", 29).As("marko").AddV("person").Property("name", " vadas ").Property("age", 27).As("vadas").AddV("software").Property("name", " lop").Property("lang", "java").As("lop").AddV("person").Property("name", "josh ").Property("age", 32).As("josh").AddV("software").Property("name", " [...]
+ "g_V_hasLabelXpersonX_labels": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.V().HasLabel("person").Labels()}},
+ "g_addVXa_bX_labels_count": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.AddV("a", "b")}, func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.V().Labels().Count()}},
+ "g_addV_labels": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.AddV()}, func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.V().Labels()}},
+ "g_E_labels": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.E().HasLabel("knows").Labels()}},
"g_injectXfeature_test_nullX_length": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.Inject("feature", "test", nil).Length()}},
"g_injectXfeature_test_nullX_lengthXlocalX": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.Inject("feature", "test", nil).Length(gremlingo.Scope.Local)}},
"g_injectXListXa_bXX_length": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.Inject([]interface{}{"a", "b"}).Length()}},
@@ -1486,6 +1492,15 @@ var translationMap = map[string][]func(g *gremlingo.GraphTraversalSource, p map[
"g_mergeV_hidden_label_key_onMatch_matched_prohibited": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.MergeV(map[interface{}]interface{}{ }).Option(gremlingo.Merge.OnMatch, p["xx1"])}},
"g_injectXlist1_list2_list3X_fold_asXmX_mergeVXselectXmX_limitXlocal_1X_unfoldX_optionXonCreate_selectXmX_rangeXlocal_1_2X_unfoldX_optionXonMatch_selectXmX_tailXlocalX_unfoldX_to_match": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.AddV("person").Property("name", "marko").Property("age", 29)}, func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.Inject(map[interface{}]interface{ [...]
"g_injectXlist1_list2_list3X_fold_asXmX_mergeVXselectXmX_limitXlocal_1X_unfoldX_optionXonCreate_selectXmX_rangeXlocal_1_2X_unfoldX_optionXonMatch_selectXmX_tailXlocalX_unfoldX_to_create": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.AddV("person").Property("name", "marko").Property("age", 29)}, func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.Inject(map[interface{}]interface [...]
+ "g_mergeVXlabel_ab_name_markoX_multilabel_create": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.MergeV(map[interface{}]interface{}{gremlingo.T.Label: []interface{}{"person", "employee"}, "name": "marko" })}, func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.V()}, func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.V().HasLabel [...]
+ "g_mergeVXlabel_abc_name_testX_multilabel_create": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.MergeV(map[interface{}]interface{}{gremlingo.T.Label: []interface{}{"a", "b", "c"}, "name": "test" })}, func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.V()}, func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.V().HasLabel("a").Ha [...]
+ "g_mergeVXlabel_ab_name_markoX_multilabel_match": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.AddV("person").AddLabel("employee").Property("name", "marko")}, func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.MergeV(map[interface{}]interface{}{gremlingo.T.Label: []interface{}{"person", "employee"}, "name": "marko" })}, func(g *gremlingo.GraphTraversalSource, p map[string]inte [...]
+ "g_mergeVXlabel_ab_name_markoX_multilabel_nomatch": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.AddV("person").Property("name", "marko")}, func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.MergeV(map[interface{}]interface{}{gremlingo.T.Label: []interface{}{"person", "employee"}, "name": "marko" })}, func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo [...]
+ "g_mergeVXlabel_person_name_markoX_optionXonMatch_label_managerX": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.AddV("person").AddLabel("employee").Property("name", "marko")}, func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.MergeV(map[interface{}]interface{}{gremlingo.T.Label: "person", "name": "marko" }).Option(gremlingo.Merge.OnMatch, map[interface{}]interface{}{gremlingo [...]
+ "g_mergeVXlabel_person_name_markoX_optionXonMatch_label_manager_directorX": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.AddV("person").Property("name", "marko")}, func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.MergeV(map[interface{}]interface{}{gremlingo.T.Label: "person", "name": "marko" }).Option(gremlingo.Merge.OnMatch, map[interface{}]interface{}{gremlingo.T.Label: [] [...]
+ "g_mergeVXlabel_person_name_markoX_optionXonMatch_label_emptyX": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.AddV("person").Property("name", "marko")}, func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.MergeV(map[interface{}]interface{}{gremlingo.T.Label: "person", "name": "marko" }).Option(gremlingo.Merge.OnMatch, map[interface{}]interface{}{gremlingo.T.Label: []interface{} [...]
+ "g_mergeVXname_markoX_optionXonCreate_label_ab_name_markoX": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.MergeV(map[interface{}]interface{}{"name": "marko" }).Option(gremlingo.Merge.OnCreate, map[interface{}]interface{}{gremlingo.T.Label: []interface{}{"person", "employee"}, "name": "marko" })}, func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.V()}, func(g *gremlingo.GraphT [...]
+ "g_mergeVXlabel_person_name_markoX_optionXonMatch_label_existingX": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.AddV("person").AddLabel("employee").Property("name", "marko")}, func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.MergeV(map[interface{}]interface{}{gremlingo.T.Label: "person", "name": "marko" }).Option(gremlingo.Merge.OnMatch, map[interface{}]interface{}{gremling [...]
"g_V_age_min": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.V().Values("age").Min()}},
"g_V_foo_min": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.V().Values("foo").Min()}},
"g_V_name_min": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.V().Values("name").Min()}},
@@ -1971,6 +1986,10 @@ var translationMap = map[string][]func(g *gremlingo.GraphTraversalSource, p map[
"g_V_out_out_properties_asXheadX_path_order_byXdescX_selectXheadX_value": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.V().Out().Out().Properties().As("head").Path().Order().By(gremlingo.Order.Desc).Select("head").Value()}},
"g_V_out_out_values_asXheadX_path_order_byXascX_selectXheadX": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.V().Out().Out().Values().As("head").Path().Order().By(gremlingo.Order.Asc).Select("head")}},
"g_V_out_out_values_asXheadX_path_order_byXdescX_selectXheadX": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.V().Out().Out().Values().As("head").Path().Order().By(gremlingo.Order.Desc).Select("head")}},
+ "g_V_hasLabelXpersonX_hasXname_markoX_addLabelXemployeeX_labels": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.AddV("person").Property("name", "marko")}, func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.V().HasLabel("person").Has("name", "marko").AddLabel("employee").Labels().Fold()}, func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal [...]
+ "g_V_addLabelXa_bX_labels_count": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.AddV("person")}, func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.V().AddLabel("a", "b").Labels().Count()}},
+ "g_V_addLabelXexistingX_labels_count": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.AddV("person")}, func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.V().AddLabel("person").Labels().Count()}},
+ "g_E_addLabelXfriendX_labels_fold": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.AddV("person").Property("name", "marko").As("a").AddV("person").Property("name", "josh").As("b").AddE("knows").From("a").To("b")}, func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.E().AddLabel("friend").Labels().Fold()}},
"g_V_valueXnameX_aggregateXxX_capXxX": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.V().Values("name").Aggregate("x").Cap("x")}},
"g_V_aggregateXxX_byXnameX_capXxX": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.V().Aggregate("x").By("name").Cap("x")}},
"g_V_out_aggregateXaX_path": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.V().Out().Aggregate("a").Path()}},
@@ -2028,6 +2047,13 @@ var translationMap = map[string][]func(g *gremlingo.GraphTraversalSource, p map[
"g_V_repeatXaggregateXaXX_timesX2X_capXaX_unfold": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.V().Repeat(gremlingo.T__.Aggregate("a")).Times(2).Cap("a").Unfold()}},
"g_V_aggregateXaX_capXaX_unfold_both": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.V().Aggregate("a").Cap("a").Unfold().Both()}},
"g_V_aggregateXaX_capXaX_unfold_barrier_both": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.V().Aggregate("a").Cap("a").Unfold().Barrier().Both()}},
+ "g_V_dropLabelXaX_labels": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.AddV("a", "b")}, func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.V().DropLabel("a").Labels().Fold()}, func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.V().HasLabel("a")}, func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.Gra [...]
+ "g_V_dropLabels_labels": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.AddV("a", "b")}, func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.V().DropLabels().Labels()}},
+ "g_V_dropLabelXa_bX_labels": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.AddV("a", "b", "c")}, func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.V().DropLabel("a", "b").Labels()}},
+ "g_V_dropLabels_defaultLabel": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.AddV("person")}, func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.V().DropLabels().Labels()}},
+ "g_E_dropLabelXknowsX_labels": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.AddV("person").As("a").AddV("person").As("b").AddE("knows").From("a").To("b")}, func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.E().DropLabel("knows").Labels().Fold()}},
+ "g_E_dropLabels_labels": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.AddV("person").As("a").AddV("person").As("b").AddE("knows").From("a").To("b")}, func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.E().DropLabels().Labels()}},
+ "g_V_dropLabelXnonExistentX_labels": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.AddV("a", "b")}, func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.V().DropLabel("xyz").Labels()}},
"g_V_fail": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.V().Fail()}},
"g_V_failXmsgX": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.V().Fail("msg")}},
"g_V_unionXout_failX": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.V().Union(gremlingo.T__.Out(), gremlingo.T__.Fail())}},
diff --git a/gremlin-go/driver/graph.go b/gremlin-go/driver/graph.go
index 981a7fc2d3..1431b3f41b 100644
--- a/gremlin-go/driver/graph.go
+++ b/gremlin-go/driver/graph.go
@@ -57,13 +57,15 @@ type Element struct {
// Vertex contains a single Vertex which has a Label and an Id.
type Vertex struct {
Element
+ Labels []string // All labels; Element.Label still holds first label for compat
}
// Edge links two Vertex structs along with its Property Objects. An edge has both a direction and a Label.
type Edge struct {
Element
- OutV Vertex
- InV Vertex
+ OutV Vertex
+ InV Vertex
+ Labels []string // All labels
}
// VertexProperty is similar to property in that it denotes a key/value pair associated with a Vertex, but is different
diff --git a/gremlin-go/driver/graphBinaryDeserializer.go b/gremlin-go/driver/graphBinaryDeserializer.go
index 1d5b5bda09..8b95e8e38d 100644
--- a/gremlin-go/driver/graphBinaryDeserializer.go
+++ b/gremlin-go/driver/graphBinaryDeserializer.go
@@ -369,7 +369,13 @@ func (d *GraphBinaryDeserializer) readVertex(withProps bool) (*Vertex, error) {
if !ok {
return nil, newError(err0404ReadNullTypeError)
}
- v := &Vertex{Element: Element{Id: id, Label: label}}
+ allLabels := make([]string, 0, len(labelSlice))
+ for _, l := range labelSlice {
+ if s, ok := l.(string); ok {
+ allLabels = append(allLabels, s)
+ }
+ }
+ v := &Vertex{Element: Element{Id: id, Label: label}, Labels: allLabels}
if withProps {
props, err := d.ReadFullyQualified()
if err != nil {
@@ -400,6 +406,12 @@ func (d *GraphBinaryDeserializer) readEdge() (*Edge, error) {
if !ok {
return nil, newError(err0404ReadNullTypeError)
}
+ allLabels := make([]string, 0, len(labelSlice))
+ for _, l := range labelSlice {
+ if s, ok := l.(string); ok {
+ allLabels = append(allLabels, s)
+ }
+ }
inV, err := d.readVertex(false)
if err != nil {
return nil, err
@@ -419,6 +431,7 @@ func (d *GraphBinaryDeserializer) readEdge() (*Edge, error) {
Element: Element{Id: id, Label: label},
InV: *inV,
OutV: *outV,
+ Labels: allLabels,
}
e.Properties = make([]interface{}, 0)
if props != nil {
diff --git a/gremlin-go/driver/graphBinarySerializer.go b/gremlin-go/driver/graphBinarySerializer.go
index 5da2327d49..c5010a8960 100644
--- a/gremlin-go/driver/graphBinarySerializer.go
+++ b/gremlin-go/driver/graphBinarySerializer.go
@@ -267,8 +267,12 @@ func vertexWriter(value interface{}, w io.Writer, typeSerializer *graphBinaryTyp
return err
}
- // Not fully qualified.
- if err := typeSerializer.writeValue([1]string{v.Label}, w, false); err != nil {
+ // Write all labels as a list. Use Labels slice if populated, otherwise fall back to single Label.
+ labels := v.Labels
+ if len(labels) == 0 {
+ labels = []string{v.Label}
+ }
+ if err := typeSerializer.writeValue(labels, w, false); err != nil {
return err
}
// Note that as TinkerPop currently send "references" only, properties will always be null
@@ -283,8 +287,12 @@ func edgeWriter(value interface{}, w io.Writer, typeSerializer *graphBinaryTypeS
return err
}
- // Not fully qualified
- if err := typeSerializer.writeValue([1]string{e.Label}, w, false); err != nil {
+ // Write all labels as a list. Use Labels slice if populated, otherwise fall back to single Label.
+ labels := e.Labels
+ if len(labels) == 0 {
+ labels = []string{e.Label}
+ }
+ if err := typeSerializer.writeValue(labels, w, false); err != nil {
return err
}
@@ -293,8 +301,12 @@ func edgeWriter(value interface{}, w io.Writer, typeSerializer *graphBinaryTypeS
return err
}
- // Not fully qualified.
- if err := typeSerializer.writeValue([1]string{e.InV.Label}, w, false); err != nil {
+ // Write in-vertex labels
+ inVLabels := e.InV.Labels
+ if len(inVLabels) == 0 {
+ inVLabels = []string{e.InV.Label}
+ }
+ if err := typeSerializer.writeValue(inVLabels, w, false); err != nil {
return err
}
// Write out-vertex
@@ -302,8 +314,12 @@ func edgeWriter(value interface{}, w io.Writer, typeSerializer *graphBinaryTypeS
return err
}
- // Not fully qualified.
- if err := typeSerializer.writeValue([1]string{e.OutV.Label}, w, false); err != nil {
+ // Write out-vertex labels
+ outVLabels := e.OutV.Labels
+ if len(outVLabels) == 0 {
+ outVLabels = []string{e.OutV.Label}
+ }
+ if err := typeSerializer.writeValue(outVLabels, w, false); err != nil {
return err
}
diff --git a/gremlin-go/driver/graphTraversal.go b/gremlin-go/driver/graphTraversal.go
index 6a90dc6f7f..22f12bcd09 100644
--- a/gremlin-go/driver/graphTraversal.go
+++ b/gremlin-go/driver/graphTraversal.go
@@ -77,6 +77,12 @@ func (g *GraphTraversal) AddE(args ...interface{}) *GraphTraversal {
return g
}
+// AddLabel adds the addLabel step to the GraphTraversal.
+func (g *GraphTraversal) AddLabel(args ...interface{}) *GraphTraversal {
+ g.GremlinLang.AddStep("addLabel", args...)
+ return g
+}
+
// AddV adds the addV step to the GraphTraversal.
func (g *GraphTraversal) AddV(args ...interface{}) *GraphTraversal {
g.GremlinLang.AddStep("addV", args...)
@@ -289,6 +295,18 @@ func (g *GraphTraversal) Drop(args ...interface{}) *GraphTraversal {
return g
}
+// DropLabel adds the dropLabel step to the GraphTraversal.
+func (g *GraphTraversal) DropLabel(args ...interface{}) *GraphTraversal {
+ g.GremlinLang.AddStep("dropLabel", args...)
+ return g
+}
+
+// DropLabels adds the dropLabels step to the GraphTraversal.
+func (g *GraphTraversal) DropLabels(args ...interface{}) *GraphTraversal {
+ g.GremlinLang.AddStep("dropLabels", args...)
+ return g
+}
+
// Element adds the element step to the GraphTraversal.
func (g *GraphTraversal) Element(args ...interface{}) *GraphTraversal {
g.GremlinLang.AddStep("element", args...)
@@ -464,6 +482,12 @@ func (g *GraphTraversal) Label(args ...interface{}) *GraphTraversal {
return g
}
+// Labels adds the labels step to the GraphTraversal.
+func (g *GraphTraversal) Labels(args ...interface{}) *GraphTraversal {
+ g.GremlinLang.AddStep("labels", args...)
+ return g
+}
+
// Length adds the length step to the GraphTraversal.
func (g *GraphTraversal) Length(args ...interface{}) *GraphTraversal {
g.GremlinLang.AddStep("length", args...)
diff --git a/gremlin-go/driver/graph_test.go b/gremlin-go/driver/graph_test.go
index 0de4a1bac9..5599857d7f 100644
--- a/gremlin-go/driver/graph_test.go
+++ b/gremlin-go/driver/graph_test.go
@@ -30,7 +30,7 @@ import (
func TestGraphStructureFunctions(t *testing.T) {
t.Run("Test Vertex.String()", func(t *testing.T) {
uid, _ := uuid.NewUUID()
- v := Vertex{Element{uid, "Vertex-Label", nil}}
+ v := Vertex{Element: Element{uid, "Vertex-Label", nil}}
assert.Equal(t, fmt.Sprintf("v[%s]", uid.String()), v.String())
})
@@ -38,14 +38,14 @@ func TestGraphStructureFunctions(t *testing.T) {
uidEdge, _ := uuid.NewUUID()
uidIn, _ := uuid.NewUUID()
uidOut, _ := uuid.NewUUID()
- v := Edge{Element{uidEdge, "edge_label", nil}, Vertex{Element{uidOut, "vertex_out", nil}}, Vertex{Element{uidIn, "vertex_in", nil}}}
+ v := Edge{Element: Element{uidEdge, "edge_label", nil}, OutV: Vertex{Element: Element{uidOut, "vertex_out", nil}}, InV: Vertex{Element: Element{uidIn, "vertex_in", nil}}}
assert.Equal(t, fmt.Sprintf("e[%s][%s-edge_label->%s]", uidEdge.String(), uidOut.String(), uidIn.String()), v.String())
})
t.Run("Test VertexProperty.String()", func(t *testing.T) {
uidVProp, _ := uuid.NewUUID()
uidV, _ := uuid.NewUUID()
- v := VertexProperty{Element{uidVProp, "Vertex-prop", nil}, "Vertex", []uint32{0, 1}, Vertex{Element{uidV, "Vertex", nil}}}
+ v := VertexProperty{Element{uidVProp, "Vertex-prop", nil}, "Vertex", []uint32{0, 1}, Vertex{Element: Element{uidV, "Vertex", nil}}}
assert.Equal(t, "vp[Vertex-prop->[0 1]]", v.String())
})
diff --git a/gremlin-js/gremlin-javascript/lib/process/graph-traversal.ts b/gremlin-js/gremlin-javascript/lib/process/graph-traversal.ts
index b82f8c9362..2079464029 100644
--- a/gremlin-js/gremlin-javascript/lib/process/graph-traversal.ts
+++ b/gremlin-js/gremlin-javascript/lib/process/graph-traversal.ts
@@ -430,6 +430,16 @@ export class GraphTraversal extends Traversal {
return this;
}
+ /**
+ * Graph traversal addLabel method.
+ * @param {...Object} args
+ * @returns {GraphTraversal}
+ */
+ addLabel(...args: any[]): this {
+ this.gremlinLang.addStep('addLabel', args);
+ return this;
+ }
+
/**
* Graph traversal aggregate method.
* @param {...Object} args
@@ -769,6 +779,26 @@ export class GraphTraversal extends Traversal {
return this;
}
+ /**
+ * Graph traversal dropLabel method.
+ * @param {...Object} args
+ * @returns {GraphTraversal}
+ */
+ dropLabel(...args: any[]): this {
+ this.gremlinLang.addStep('dropLabel', args);
+ return this;
+ }
+
+ /**
+ * Graph traversal dropLabels method.
+ * @param {...Object} args
+ * @returns {GraphTraversal}
+ */
+ dropLabels(...args: any[]): this {
+ this.gremlinLang.addStep('dropLabels', args);
+ return this;
+ }
+
/**
* Graph traversal element method.
* @param {...Object} args
@@ -1053,6 +1083,16 @@ export class GraphTraversal extends Traversal {
return this;
}
+ /**
+ * Graph traversal labels method.
+ * @param {...Object} args
+ * @returns {GraphTraversal}
+ */
+ labels(...args: any[]): this {
+ this.gremlinLang.addStep('labels', args);
+ return this;
+ }
+
/**
* Graph traversal length method.
* @param {...Object} args
@@ -1825,6 +1865,7 @@ export const statics = {
V: (...args: any[]) => callOnEmptyTraversal('V', args),
addE: (...args: any[]) => callOnEmptyTraversal('addE', args),
addV: (...args: any[]) => callOnEmptyTraversal('addV', args),
+ addLabel: (...args: any[]) => callOnEmptyTraversal('addLabel', args),
aggregate: (...args: any[]) => callOnEmptyTraversal('aggregate', args),
all: (...args: any[]) => callOnEmptyTraversal('all', args),
and: (...args: any[]) => callOnEmptyTraversal('and', args),
@@ -1857,6 +1898,8 @@ export const statics = {
discard: (...args: any[]) => callOnEmptyTraversal('discard', args),
disjunct: (...args: any[]) => callOnEmptyTraversal('disjunct', args),
drop: (...args: any[]) => callOnEmptyTraversal('drop', args),
+ dropLabel: (...args: any[]) => callOnEmptyTraversal('dropLabel', args),
+ dropLabels: (...args: any[]) => callOnEmptyTraversal('dropLabels', args),
element: (...args: any[]) => callOnEmptyTraversal('element', args),
elementMap: (...args: any[]) => callOnEmptyTraversal('elementMap', args),
emit: (...args: any[]) => callOnEmptyTraversal('emit', args),
@@ -1884,6 +1927,7 @@ export const statics = {
is: (...args: any[]) => callOnEmptyTraversal('is', args),
key: (...args: any[]) => callOnEmptyTraversal('key', args),
label: (...args: any[]) => callOnEmptyTraversal('label', args),
+ labels: (...args: any[]) => callOnEmptyTraversal('labels', args),
length: (...args: any[]) => callOnEmptyTraversal('length', args),
limit: (...args: any[]) => callOnEmptyTraversal('limit', args),
local: (...args: any[]) => callOnEmptyTraversal('local', args),
diff --git a/gremlin-js/gremlin-javascript/lib/structure/graph.ts b/gremlin-js/gremlin-javascript/lib/structure/graph.ts
index 75baa70014..954c97cbc9 100644
--- a/gremlin-js/gremlin-javascript/lib/structure/graph.ts
+++ b/gremlin-js/gremlin-javascript/lib/structure/graph.ts
@@ -67,12 +67,23 @@ export class Vertex<
[P in keyof TProperties]: P extends string ? VertexProperties<P, TProperties[P]> : never;
},
> extends Element<TLabel, TId> {
+ readonly labels: Set<string>;
+
constructor(
id: TId,
- label: TLabel,
+ label: TLabel | string[],
properties: Property[] | null = [],
+ labels?: string[],
) {
- super(id, label, properties ?? []);
+ // Determine the canonical labels array from either explicit labels param or label param
+ const resolvedLabels: string[] = labels
+ ? labels
+ : Array.isArray(label) ? label
+ : label ? [label as string]
+ : ['vertex'];
+ const primaryLabel = (resolvedLabels.length > 0 ? resolvedLabels[0] : 'vertex') as TLabel;
+ super(id, primaryLabel, properties ?? []);
+ this.labels = new Set(resolvedLabels);
}
toString() {
@@ -87,14 +98,25 @@ export class Edge<
TProperties extends Record<string, any> = Record<string, any>,
TId = number,
> extends Element<TLabel, TId> {
+ readonly labels: Set<string>;
+
constructor(
id: TId,
readonly outV: TOutVertex,
- readonly label: TLabel,
+ label: TLabel | string[],
readonly inV: TInVertex,
properties: Property[] | null = [],
+ labels?: string[],
) {
- super(id, label, properties ?? []);
+ // Determine the canonical labels array from either explicit labels param or label param
+ const resolvedLabels: string[] = labels
+ ? labels
+ : Array.isArray(label) ? label
+ : label ? [label as string]
+ : ['edge'];
+ const primaryLabel = (resolvedLabels.length > 0 ? resolvedLabels[0] : 'edge') as TLabel;
+ super(id, primaryLabel, properties ?? []);
+ this.labels = new Set(resolvedLabels);
}
toString() {
diff --git a/gremlin-js/gremlin-javascript/lib/structure/io/binary/internals/EdgeSerializer.js b/gremlin-js/gremlin-javascript/lib/structure/io/binary/internals/EdgeSerializer.js
index 5ec2307b01..88d1a2ee53 100644
--- a/gremlin-js/gremlin-javascript/lib/structure/io/binary/internals/EdgeSerializer.js
+++ b/gremlin-js/gremlin-javascript/lib/structure/io/binary/internals/EdgeSerializer.js
@@ -59,7 +59,14 @@ export default class EdgeSerializer {
bufs.push(this.ioc.anySerializer.serialize(item.id));
// {label}
- const labels = Array.isArray(item.label) ? item.label : item.label ? [item.label] : [];
+ const labels =
+ item.labels instanceof Set
+ ? Array.from(item.labels)
+ : Array.isArray(item.label)
+ ? item.label
+ : item.label
+ ? [item.label]
+ : [];
bufs.push(this.ioc.listSerializer.serialize(labels, false));
// {inVId}
@@ -67,8 +74,14 @@ export default class EdgeSerializer {
bufs.push(this.ioc.anySerializer.serialize(inVId));
// {inVLabel}
- const inVLabel = item.inV && item.inV.label;
- const inVLabels = Array.isArray(inVLabel) ? inVLabel : inVLabel ? [inVLabel] : [];
+ const inVLabels =
+ item.inV && item.inV.labels instanceof Set
+ ? Array.from(item.inV.labels)
+ : item.inV && Array.isArray(item.inV.label)
+ ? item.inV.label
+ : item.inV && item.inV.label
+ ? [item.inV.label]
+ : [];
bufs.push(this.ioc.listSerializer.serialize(inVLabels, false));
// {outVId}
@@ -76,8 +89,14 @@ export default class EdgeSerializer {
bufs.push(this.ioc.anySerializer.serialize(outVId));
// {outVLabel}
- const outVLabel = item.outV && item.outV.label;
- const outVLabels = Array.isArray(outVLabel) ? outVLabel : outVLabel ? [outVLabel] : [];
+ const outVLabels =
+ item.outV && item.outV.labels instanceof Set
+ ? Array.from(item.outV.labels)
+ : item.outV && Array.isArray(item.outV.label)
+ ? item.outV.label
+ : item.outV && item.outV.label
+ ? [item.outV.label]
+ : [];
bufs.push(this.ioc.listSerializer.serialize(outVLabels, false));
// {parent}
@@ -100,23 +119,26 @@ export default class EdgeSerializer {
// {id} fully qualified
const id = await this.ioc.anySerializer.deserialize(reader);
- // {label} bare list, extract first element
+ // {label} bare list - full multi-label list
const labelList = await this.ioc.listSerializer.deserializeValue(reader, 0x00, this.ioc.DataType.LIST);
- const label = Array.isArray(labelList) && labelList.length > 0 ? labelList[0] : labelList;
+ const labels = Array.isArray(labelList) ? labelList : labelList ? [labelList] : [];
+ const label = labels.length > 0 ? labels[0] : 'edge';
// {inVId} fully qualified
const inVId = await this.ioc.anySerializer.deserialize(reader);
- // {inVLabel} bare list, extract first element
+ // {inVLabel} bare list - full multi-label list
const inVLabelList = await this.ioc.listSerializer.deserializeValue(reader, 0x00, this.ioc.DataType.LIST);
- const inVLabel = Array.isArray(inVLabelList) && inVLabelList.length > 0 ? inVLabelList[0] : inVLabelList;
+ const inVLabels = Array.isArray(inVLabelList) ? inVLabelList : inVLabelList ? [inVLabelList] : [];
+ const inVLabel = inVLabels.length > 0 ? inVLabels[0] : 'vertex';
// {outVId} fully qualified
const outVId = await this.ioc.anySerializer.deserialize(reader);
- // {outVLabel} bare list, extract first element
+ // {outVLabel} bare list - full multi-label list
const outVLabelList = await this.ioc.listSerializer.deserializeValue(reader, 0x00, this.ioc.DataType.LIST);
- const outVLabel = Array.isArray(outVLabelList) && outVLabelList.length > 0 ? outVLabelList[0] : outVLabelList;
+ const outVLabels = Array.isArray(outVLabelList) ? outVLabelList : outVLabelList ? [outVLabelList] : [];
+ const outVLabel = outVLabels.length > 0 ? outVLabels[0] : 'vertex';
// {parent} fully qualified (always null in current TinkerPop)
await this.ioc.anySerializer.deserialize(reader);
@@ -126,10 +148,11 @@ export default class EdgeSerializer {
return new Edge(
id,
- new Vertex(outVId, outVLabel, null),
+ new Vertex(outVId, outVLabel, null, outVLabels),
label,
- new Vertex(inVId, inVLabel, null),
+ new Vertex(inVId, inVLabel, null, inVLabels),
properties || [],
+ labels,
);
}
diff --git a/gremlin-js/gremlin-javascript/lib/structure/io/binary/internals/GraphSerializer.js b/gremlin-js/gremlin-javascript/lib/structure/io/binary/internals/GraphSerializer.js
index abf8ac5e2e..5c843b4445 100644
--- a/gremlin-js/gremlin-javascript/lib/structure/io/binary/internals/GraphSerializer.js
+++ b/gremlin-js/gremlin-javascript/lib/structure/io/binary/internals/GraphSerializer.js
@@ -56,8 +56,9 @@ export default class GraphSerializer {
// {id}
bufs.push(this.ioc.anySerializer.serialize(v.id));
- // {label} as 1-element list (value-only)
- bufs.push(this.ioc.listSerializer.serialize([v.label], false));
+ // {label} as list (value-only)
+ const vLabels = v.labels instanceof Set ? Array.from(v.labels) : [v.label];
+ bufs.push(this.ioc.listSerializer.serialize(vLabels, false));
const vps = Array.isArray(v.properties) ? v.properties : [];
@@ -91,8 +92,9 @@ export default class GraphSerializer {
// {id}
bufs.push(this.ioc.anySerializer.serialize(e.id));
- // {label} as 1-element list (value-only)
- bufs.push(this.ioc.listSerializer.serialize([e.label], false));
+ // {label} as list (value-only)
+ const eLabels = e.labels instanceof Set ? Array.from(e.labels) : [e.label];
+ bufs.push(this.ioc.listSerializer.serialize(eLabels, false));
// {inV_id}
bufs.push(this.ioc.anySerializer.serialize(e.inV && e.inV.id));
@@ -133,11 +135,12 @@ export default class GraphSerializer {
// {id} fully qualified
const vId = await this.ioc.anySerializer.deserialize(reader);
- // {label} value-only list, first element
+ // {label} value-only list - full multi-label list
const vLabelList = await this.ioc.listSerializer.deserializeValue(reader, 0x00, this.ioc.DataType.LIST);
- const vLabel = Array.isArray(vLabelList) && vLabelList.length > 0 ? vLabelList[0] : vLabelList;
+ const vLabels = Array.isArray(vLabelList) ? vLabelList : vLabelList ? [vLabelList] : [];
+ const vLabel = vLabels.length > 0 ? vLabels[0] : 'vertex';
- const vertex = new Vertex(vId, vLabel, []);
+ const vertex = new Vertex(vId, vLabel, [], vLabels);
graph.vertices.set(vId, vertex);
// {vp_count} bare int
@@ -170,9 +173,10 @@ export default class GraphSerializer {
// {id} fully qualified
const eId = await this.ioc.anySerializer.deserialize(reader);
- // {label} value-only list, first element
+ // {label} value-only list - full multi-label list
const eLabelList = await this.ioc.listSerializer.deserializeValue(reader, 0x00, this.ioc.DataType.LIST);
- const eLabel = Array.isArray(eLabelList) && eLabelList.length > 0 ? eLabelList[0] : eLabelList;
+ const eLabels = Array.isArray(eLabelList) ? eLabelList : eLabelList ? [eLabelList] : [];
+ const eLabel = eLabels.length > 0 ? eLabels[0] : 'edge';
// {inV_id} fully qualified
const inVId = await this.ioc.anySerializer.deserialize(reader);
@@ -196,7 +200,7 @@ export default class GraphSerializer {
const inV = graph.vertices.get(inVId) || new Vertex(inVId, '', []);
const outV = graph.vertices.get(outVId) || new Vertex(outVId, '', []);
- const edge = new Edge(eId, outV, eLabel, inV, edgeProps || []);
+ const edge = new Edge(eId, outV, eLabel, inV, edgeProps || [], eLabels);
graph.edges.set(eId, edge);
}
diff --git a/gremlin-js/gremlin-javascript/lib/structure/io/binary/internals/VertexSerializer.js b/gremlin-js/gremlin-javascript/lib/structure/io/binary/internals/VertexSerializer.js
index 49771247d0..4c64e1df8d 100644
--- a/gremlin-js/gremlin-javascript/lib/structure/io/binary/internals/VertexSerializer.js
+++ b/gremlin-js/gremlin-javascript/lib/structure/io/binary/internals/VertexSerializer.js
@@ -54,7 +54,14 @@ export default class VertexSerializer {
bufs.push(this.ioc.anySerializer.serialize(item.id));
// {label}
- const labels = Array.isArray(item.label) ? item.label : item.label ? [item.label] : [];
+ const labels =
+ item.labels instanceof Set
+ ? Array.from(item.labels)
+ : Array.isArray(item.label)
+ ? item.label
+ : item.label
+ ? [item.label]
+ : [];
bufs.push(this.ioc.listSerializer.serialize(labels, false));
// {properties}
@@ -74,14 +81,15 @@ export default class VertexSerializer {
// {id} fully qualified
const id = await this.ioc.anySerializer.deserialize(reader);
- // {label} bare list, extract first element
+ // {label} bare list - full multi-label list
const labelList = await this.ioc.listSerializer.deserializeValue(reader, 0x00, this.ioc.DataType.LIST);
- const label = Array.isArray(labelList) && labelList.length > 0 ? labelList[0] : labelList;
+ const labels = Array.isArray(labelList) ? labelList : labelList ? [labelList] : [];
+ const label = labels.length > 0 ? labels[0] : 'vertex';
// {properties} fully qualified
const properties = await this.ioc.anySerializer.deserialize(reader);
- return new Vertex(id, label, properties || []);
+ return new Vertex(id, label, properties || [], labels);
}
/**
diff --git a/gremlin-js/gremlin-javascript/test/cucumber/gremlin.js b/gremlin-js/gremlin-javascript/test/cucumber/gremlin.js
index d4e6e97e75..97df92ce24 100644
--- a/gremlin-js/gremlin-javascript/test/cucumber/gremlin.js
+++ b/gremlin-js/gremlin-javascript/test/cucumber/gremlin.js
@@ -957,6 +957,8 @@ const gremlins = {
g_V_limitX3X_addVXsoftwareX_aggregateXa1X_byXlabelX_aggregateXa2X_byXlabelX_capXa1_a2X_selectXa_bX_byXunfoldX_foldX: [function({g}) { return g.addV("person").property("name", "marko").property("age", 29).as("marko").addV("person").property("name", "vadas").property("age", 27).as("vadas").addV("software").property("name", "lop").property("lang", "java").as("lop").addV("person").property("name", "josh").property("age", 32).as("josh").addV("software").property("name", "ripple").property [...]
g_addV_propertyXname_markoX_withXkey_valueX_valuesXname_keyX: [function({g}) { return g.addV().property("name", "marko").with_("key", "value").values("name", "key") }],
g_addV_propertyXname_marko_since_2010X_withXkey_valueX_propertiesXnameX_valuesXsince_keyX: [function({g}) { return g.addV().property("name", "marko", "since", 2010).with_("key", "value").properties("name").values("since", "key") }],
+ g_addVXa_bX_labels: [function({g}) { return g.addV("a", "b").labels().fold() }, function({g}) { return g.V().hasLabel("a").hasLabel("b") }, function({g}) { return g.addV("a", "b") }, function({g}) { return g.V().labels() }],
+ g_addVXa_b_cX_labels_count: [function({g}) { return g.addV("a", "b", "c").labels().count() }],
g_injectX1X_asBool: [function({g}) { return g.inject(1).asBool() }],
g_injectX3_14X_asBool: [function({g}) { return g.inject(3.14).asBool() }],
g_injectXneg_1X_asBool: [function({g}) { return g.inject(-1).asBool() }],
@@ -1251,6 +1253,10 @@ const gremlins = {
g_injectXListX1_2XX_lTrimXlocalX: [function({g}) { return g.inject([1, 2]).lTrim(Scope.local) }],
g_V_valuesXnameX_lTrim: [function({g}) { return g.addV("person").property("name", " marko ").property("age", 29).as("marko").addV("person").property("name", " vadas ").property("age", 27).as("vadas").addV("software").property("name", " lop").property("lang", "java").as("lop").addV("person").property("name", "josh ").property("age", 32).as("josh").addV("software").property("name", " ripple ").property("lang", "java").as("ripple").addV("person").property("name", "peter").proper [...]
g_V_valuesXnameX_order_fold_lTrimXlocalX: [function({g}) { return g.addV("person").property("name", " marko ").property("age", 29).as("marko").addV("person").property("name", " vadas ").property("age", 27).as("vadas").addV("software").property("name", " lop").property("lang", "java").as("lop").addV("person").property("name", "josh ").property("age", 32).as("josh").addV("software").property("name", " ripple ").property("lang", "java").as("ripple").addV("person").property("name [...]
+ g_V_hasLabelXpersonX_labels: [function({g}) { return g.V().hasLabel("person").labels() }],
+ g_addVXa_bX_labels_count: [function({g}) { return g.addV("a", "b") }, function({g}) { return g.V().labels().count() }],
+ g_addV_labels: [function({g}) { return g.addV() }, function({g}) { return g.V().labels() }],
+ g_E_labels: [function({g}) { return g.E().hasLabel("knows").labels() }],
g_injectXfeature_test_nullX_length: [function({g}) { return g.inject("feature", "test", null).length() }],
g_injectXfeature_test_nullX_lengthXlocalX: [function({g}) { return g.inject("feature", "test", null).length(Scope.local) }],
g_injectXListXa_bXX_length: [function({g}) { return g.inject(["a", "b"]).length() }],
@@ -1517,6 +1523,15 @@ const gremlins = {
g_mergeV_hidden_label_key_onMatch_matched_prohibited: [function({g, xx1}) { return g.mergeV(new Map([])).option(Merge.onMatch, xx1) }],
g_injectXlist1_list2_list3X_fold_asXmX_mergeVXselectXmX_limitXlocal_1X_unfoldX_optionXonCreate_selectXmX_rangeXlocal_1_2X_unfoldX_optionXonMatch_selectXmX_tailXlocalX_unfoldX_to_match: [function({g}) { return g.addV("person").property("name", "marko").property("age", 29) }, function({g}) { return g.inject(new Map([[T.label, "person"], ["name", "marko"]]), new Map([[T.label, "person"], ["name", "marko"]]), new Map([["created", "N"]])).fold().as("m").mergeV(__.select("m").limit(Scope.l [...]
g_injectXlist1_list2_list3X_fold_asXmX_mergeVXselectXmX_limitXlocal_1X_unfoldX_optionXonCreate_selectXmX_rangeXlocal_1_2X_unfoldX_optionXonMatch_selectXmX_tailXlocalX_unfoldX_to_create: [function({g}) { return g.addV("person").property("name", "marko").property("age", 29) }, function({g}) { return g.inject(new Map([[T.label, "person"], ["name", "stephen"]]), new Map([[T.label, "person"], ["name", "stephen"]]), new Map([["created", "N"]])).fold().as("m").mergeV(__.select("m").limit(Sc [...]
+ g_mergeVXlabel_ab_name_markoX_multilabel_create: [function({g}) { return g.mergeV(new Map([[T.label, ["person", "employee"]], ["name", "marko"]])) }, function({g}) { return g.V() }, function({g}) { return g.V().hasLabel("person").hasLabel("employee") }, function({g}) { return g.V().has("name", "marko") }],
+ g_mergeVXlabel_abc_name_testX_multilabel_create: [function({g}) { return g.mergeV(new Map([[T.label, ["a", "b", "c"]], ["name", "test"]])) }, function({g}) { return g.V() }, function({g}) { return g.V().hasLabel("a").hasLabel("b").hasLabel("c") }],
+ g_mergeVXlabel_ab_name_markoX_multilabel_match: [function({g}) { return g.addV("person").addLabel("employee").property("name", "marko") }, function({g}) { return g.mergeV(new Map([[T.label, ["person", "employee"]], ["name", "marko"]])) }, function({g}) { return g.V() }, function({g}) { return g.V().hasLabel("person").hasLabel("employee") }],
+ g_mergeVXlabel_ab_name_markoX_multilabel_nomatch: [function({g}) { return g.addV("person").property("name", "marko") }, function({g}) { return g.mergeV(new Map([[T.label, ["person", "employee"]], ["name", "marko"]])) }, function({g}) { return g.V() }],
+ g_mergeVXlabel_person_name_markoX_optionXonMatch_label_managerX: [function({g}) { return g.addV("person").addLabel("employee").property("name", "marko") }, function({g}) { return g.mergeV(new Map([[T.label, "person"], ["name", "marko"]])).option(Merge.onMatch, new Map([[T.label, "manager"]])) }, function({g}) { return g.V() }, function({g}) { return g.V().hasLabel("manager") }, function({g}) { return g.V().hasLabel("person") }, function({g}) { return g.V().hasLabel("employee") }],
+ g_mergeVXlabel_person_name_markoX_optionXonMatch_label_manager_directorX: [function({g}) { return g.addV("person").property("name", "marko") }, function({g}) { return g.mergeV(new Map([[T.label, "person"], ["name", "marko"]])).option(Merge.onMatch, new Map([[T.label, ["manager", "director"]]])) }, function({g}) { return g.V() }, function({g}) { return g.V().hasLabel("manager").hasLabel("director") }, function({g}) { return g.V().hasLabel("person") }],
+ g_mergeVXlabel_person_name_markoX_optionXonMatch_label_emptyX: [function({g}) { return g.addV("person").property("name", "marko") }, function({g}) { return g.mergeV(new Map([[T.label, "person"], ["name", "marko"]])).option(Merge.onMatch, new Map([[T.label, []]])) }, function({g}) { return g.V() }, function({g}) { return g.V().hasLabel("person") }],
+ g_mergeVXname_markoX_optionXonCreate_label_ab_name_markoX: [function({g}) { return g.mergeV(new Map([["name", "marko"]])).option(Merge.onCreate, new Map([[T.label, ["person", "employee"]], ["name", "marko"]])) }, function({g}) { return g.V() }, function({g}) { return g.V().hasLabel("person").hasLabel("employee") }, function({g}) { return g.V().has("name", "marko") }],
+ g_mergeVXlabel_person_name_markoX_optionXonMatch_label_existingX: [function({g}) { return g.addV("person").addLabel("employee").property("name", "marko") }, function({g}) { return g.mergeV(new Map([[T.label, "person"], ["name", "marko"]])).option(Merge.onMatch, new Map([[T.label, "person"]])) }, function({g}) { return g.V() }, function({g}) { return g.V().hasLabel("person").hasLabel("employee") }],
g_V_age_min: [function({g}) { return g.V().values("age").min() }],
g_V_foo_min: [function({g}) { return g.V().values("foo").min() }],
g_V_name_min: [function({g}) { return g.V().values("name").min() }],
@@ -2002,6 +2017,10 @@ const gremlins = {
g_V_out_out_properties_asXheadX_path_order_byXdescX_selectXheadX_value: [function({g}) { return g.V().out().out().properties().as("head").path().order().by(Order.desc).select("head").value() }],
g_V_out_out_values_asXheadX_path_order_byXascX_selectXheadX: [function({g}) { return g.V().out().out().values().as("head").path().order().by(Order.asc).select("head") }],
g_V_out_out_values_asXheadX_path_order_byXdescX_selectXheadX: [function({g}) { return g.V().out().out().values().as("head").path().order().by(Order.desc).select("head") }],
+ g_V_hasLabelXpersonX_hasXname_markoX_addLabelXemployeeX_labels: [function({g}) { return g.addV("person").property("name", "marko") }, function({g}) { return g.V().hasLabel("person").has("name", "marko").addLabel("employee").labels().fold() }, function({g}) { return g.V().hasLabel("person").hasLabel("employee") }],
+ g_V_addLabelXa_bX_labels_count: [function({g}) { return g.addV("person") }, function({g}) { return g.V().addLabel("a", "b").labels().count() }],
+ g_V_addLabelXexistingX_labels_count: [function({g}) { return g.addV("person") }, function({g}) { return g.V().addLabel("person").labels().count() }],
+ g_E_addLabelXfriendX_labels_fold: [function({g}) { return g.addV("person").property("name", "marko").as("a").addV("person").property("name", "josh").as("b").addE("knows").from_("a").to("b") }, function({g}) { return g.E().addLabel("friend").labels().fold() }],
g_V_valueXnameX_aggregateXxX_capXxX: [function({g}) { return g.V().values("name").aggregate("x").cap("x") }],
g_V_aggregateXxX_byXnameX_capXxX: [function({g}) { return g.V().aggregate("x").by("name").cap("x") }],
g_V_out_aggregateXaX_path: [function({g}) { return g.V().out().aggregate("a").path() }],
@@ -2059,6 +2078,13 @@ const gremlins = {
g_V_repeatXaggregateXaXX_timesX2X_capXaX_unfold: [function({g}) { return g.V().repeat(__.aggregate("a")).times(2).cap("a").unfold() }],
g_V_aggregateXaX_capXaX_unfold_both: [function({g}) { return g.V().aggregate("a").cap("a").unfold().both() }],
g_V_aggregateXaX_capXaX_unfold_barrier_both: [function({g}) { return g.V().aggregate("a").cap("a").unfold().barrier().both() }],
+ g_V_dropLabelXaX_labels: [function({g}) { return g.addV("a", "b") }, function({g}) { return g.V().dropLabel("a").labels().fold() }, function({g}) { return g.V().hasLabel("a") }, function({g}) { return g.V().hasLabel("b") }],
+ g_V_dropLabels_labels: [function({g}) { return g.addV("a", "b") }, function({g}) { return g.V().dropLabels().labels() }],
+ g_V_dropLabelXa_bX_labels: [function({g}) { return g.addV("a", "b", "c") }, function({g}) { return g.V().dropLabel("a", "b").labels() }],
+ g_V_dropLabels_defaultLabel: [function({g}) { return g.addV("person") }, function({g}) { return g.V().dropLabels().labels() }],
+ g_E_dropLabelXknowsX_labels: [function({g}) { return g.addV("person").as("a").addV("person").as("b").addE("knows").from_("a").to("b") }, function({g}) { return g.E().dropLabel("knows").labels().fold() }],
+ g_E_dropLabels_labels: [function({g}) { return g.addV("person").as("a").addV("person").as("b").addE("knows").from_("a").to("b") }, function({g}) { return g.E().dropLabels().labels() }],
+ g_V_dropLabelXnonExistentX_labels: [function({g}) { return g.addV("a", "b") }, function({g}) { return g.V().dropLabel("xyz").labels() }],
g_V_fail: [function({g}) { return g.V().fail() }],
g_V_failXmsgX: [function({g}) { return g.V().fail("msg") }],
g_V_unionXout_failX: [function({g}) { return g.V().union(__.out(), __.fail()) }],
diff --git a/gremlin-js/gremlin-mcp/src/translator/stepNames.ts b/gremlin-js/gremlin-mcp/src/translator/stepNames.ts
index 3873293afd..71525a298b 100644
--- a/gremlin-js/gremlin-mcp/src/translator/stepNames.ts
+++ b/gremlin-js/gremlin-mcp/src/translator/stepNames.ts
@@ -28,6 +28,7 @@ export const GREMLIN_STEP_NAMES: ReadonlySet<string> = new Set([
'E',
'V',
'addE',
+ 'addLabel',
'addV',
'aggregate',
'all',
@@ -62,6 +63,8 @@ export const GREMLIN_STEP_NAMES: ReadonlySet<string> = new Set([
'discard',
'disjunct',
'drop',
+ 'dropLabel',
+ 'dropLabels',
'element',
'elementMap',
'emit',
@@ -92,6 +95,7 @@ export const GREMLIN_STEP_NAMES: ReadonlySet<string> = new Set([
'key',
'lTrim',
'label',
+ 'labels',
'length',
'limit',
'local',
@@ -170,6 +174,7 @@ export const GREMLIN_STEP_NAMES_PASCAL: ReadonlySet<string> = new Set([
'E',
'V',
'AddE',
+ 'AddLabel',
'AddV',
'Aggregate',
'All',
@@ -204,6 +209,8 @@ export const GREMLIN_STEP_NAMES_PASCAL: ReadonlySet<string> = new Set([
'Discard',
'Disjunct',
'Drop',
+ 'DropLabel',
+ 'DropLabels',
'Element',
'ElementMap',
'Emit',
@@ -234,6 +241,7 @@ export const GREMLIN_STEP_NAMES_PASCAL: ReadonlySet<string> = new Set([
'Key',
'LTrim',
'Label',
+ 'Labels',
'Length',
'Limit',
'Local',
diff --git a/gremlin-python/src/main/python/gremlin_python/process/graph_traversal.py b/gremlin-python/src/main/python/gremlin_python/process/graph_traversal.py
index 411ceeb806..552c53167e 100644
--- a/gremlin-python/src/main/python/gremlin_python/process/graph_traversal.py
+++ b/gremlin-python/src/main/python/gremlin_python/process/graph_traversal.py
@@ -306,6 +306,17 @@ class GraphTraversal(Traversal):
self.gremlin_lang.add_step("addV", *args)
return self
+ def addLabel(self, *args):
+ warnings.warn(
+ "gremlin_python.process.GraphTraversal.addLabel will be replaced by "
+ "gremlin_python.process.GraphTraversal.add_label.",
+ DeprecationWarning)
+ return self.add_label(*args)
+
+ def add_label(self, *args):
+ self.gremlin_lang.add_step("addLabel", *args)
+ return self
+
def aggregate(self, *args):
self.gremlin_lang.add_step("aggregate", *args)
return self
@@ -470,6 +481,28 @@ class GraphTraversal(Traversal):
self.gremlin_lang.add_step("drop", *args)
return self
+ def dropLabel(self, *args):
+ warnings.warn(
+ "gremlin_python.process.GraphTraversal.dropLabel will be replaced by "
+ "gremlin_python.process.GraphTraversal.drop_label.",
+ DeprecationWarning)
+ return self.drop_label(*args)
+
+ def drop_label(self, *args):
+ self.gremlin_lang.add_step("dropLabel", *args)
+ return self
+
+ def dropLabels(self, *args):
+ warnings.warn(
+ "gremlin_python.process.GraphTraversal.dropLabels will be replaced by "
+ "gremlin_python.process.GraphTraversal.drop_labels.",
+ DeprecationWarning)
+ return self.drop_labels(*args)
+
+ def drop_labels(self, *args):
+ self.gremlin_lang.add_step("dropLabels", *args)
+ return self
+
def element(self, *args):
self.gremlin_lang.add_step("element", *args)
return self
@@ -662,6 +695,10 @@ class GraphTraversal(Traversal):
self.gremlin_lang.add_step("label", *args)
return self
+ def labels(self, *args):
+ self.gremlin_lang.add_step("labels", *args)
+ return self
+
def length(self, *args):
self.gremlin_lang.add_step("length", *args)
return self
@@ -1103,6 +1140,18 @@ class __(object, metaclass=MagicType):
def add_v(cls, *args):
return cls.graph_traversal(None, None, GremlinLang()).add_v(*args)
+ @classmethod
+ def addLabel(cls, *args):
+ warnings.warn(
+ "gremlin_python.process.__.addLabel will be replaced by "
+ "gremlin_python.process.__.add_label.",
+ DeprecationWarning)
+ return cls.add_label(*args)
+
+ @classmethod
+ def add_label(cls, *args):
+ return cls.graph_traversal(None, None, GremlinLang()).add_label(*args)
+
@classmethod
def aggregate(cls, *args):
return cls.graph_traversal(None, None, GremlinLang()).aggregate(*args)
@@ -1255,6 +1304,30 @@ class __(object, metaclass=MagicType):
def drop(cls, *args):
return cls.graph_traversal(None, None, GremlinLang()).drop(*args)
+ @classmethod
+ def dropLabel(cls, *args):
+ warnings.warn(
+ "gremlin_python.process.__.dropLabel will be replaced by "
+ "gremlin_python.process.__.drop_label.",
+ DeprecationWarning)
+ return cls.drop_label(*args)
+
+ @classmethod
+ def drop_label(cls, *args):
+ return cls.graph_traversal(None, None, GremlinLang()).drop_label(*args)
+
+ @classmethod
+ def dropLabels(cls, *args):
+ warnings.warn(
+ "gremlin_python.process.__.dropLabels will be replaced by "
+ "gremlin_python.process.__.drop_labels.",
+ DeprecationWarning)
+ return cls.drop_labels(*args)
+
+ @classmethod
+ def drop_labels(cls, *args):
+ return cls.graph_traversal(None, None, GremlinLang()).drop_labels(*args)
+
@classmethod
def element(cls, *args):
return cls.graph_traversal(None, None, GremlinLang()).element(*args)
@@ -1451,6 +1524,10 @@ class __(object, metaclass=MagicType):
def label(cls, *args):
return cls.graph_traversal(None, None, GremlinLang()).label(*args)
+ @classmethod
+ def labels(cls, *args):
+ return cls.graph_traversal(None, None, GremlinLang()).labels(*args)
+
@classmethod
def length(cls, *args):
return cls.graph_traversal(None, None, GremlinLang()).length(*args)
@@ -1816,6 +1893,14 @@ def add_v(*args):
return __.add_v(*args)
+def addLabel(*args):
+ return __.add_label(*args)
+
+
+def add_label(*args):
+ return __.add_label(*args)
+
+
def aggregate(*args):
return __.aggregate(*args)
@@ -1956,6 +2041,22 @@ def drop(*args):
return __.drop(*args)
+def dropLabel(*args):
+ return __.drop_label(*args)
+
+
+def drop_label(*args):
+ return __.drop_label(*args)
+
+
+def dropLabels(*args):
+ return __.drop_labels(*args)
+
+
+def drop_labels(*args):
+ return __.drop_labels(*args)
+
+
def element(*args):
return __.element(*args)
@@ -2106,6 +2207,10 @@ def label(*args):
return __.label(*args)
+def labels(*args):
+ return __.labels(*args)
+
+
def length(*args):
return __.length(*args)
@@ -2409,6 +2514,10 @@ statics.add_static('addV', addV)
statics.add_static('add_v', add_v)
+statics.add_static('addLabel', addLabel)
+
+statics.add_static('add_label', add_label)
+
statics.add_static('aggregate', aggregate)
statics.add_static('all_', all_)
@@ -2479,6 +2588,14 @@ statics.add_static('disjunct', disjunct)
statics.add_static('drop', drop)
+statics.add_static('dropLabel', dropLabel)
+
+statics.add_static('drop_label', drop_label)
+
+statics.add_static('dropLabels', dropLabels)
+
+statics.add_static('drop_labels', drop_labels)
+
statics.add_static('element', element)
statics.add_static('elementMap', elementMap)
@@ -2551,6 +2668,8 @@ statics.add_static('key', key)
statics.add_static('label', label)
+statics.add_static('labels', labels)
+
statics.add_static('length', length)
statics.add_static('limit', limit)
diff --git a/gremlin-python/src/main/python/gremlin_python/structure/graph.py b/gremlin-python/src/main/python/gremlin_python/structure/graph.py
index 619eb64899..00c22f9dab 100644
--- a/gremlin-python/src/main/python/gremlin_python/structure/graph.py
+++ b/gremlin-python/src/main/python/gremlin_python/structure/graph.py
@@ -64,19 +64,37 @@ class Element(object):
class Vertex(Element):
- def __init__(self, id, label="vertex", properties=None):
- Element.__init__(self, id, label, properties)
+ def __init__(self, id, label="vertex", properties=None, labels=None):
+ if labels is not None and len(labels) > 0:
+ self._labels = set(labels)
+ Element.__init__(self, id, next(iter(labels)), properties)
+ else:
+ self._labels = {label} if label else {"vertex"}
+ Element.__init__(self, id, label or "vertex", properties)
+
+ @property
+ def labels(self):
+ return frozenset(self._labels)
def __repr__(self):
return "v[" + str(self.id) + "]"
class Edge(Element):
- def __init__(self, id, outV, label, inV, properties=None):
- Element.__init__(self, id, label, properties)
+ def __init__(self, id, outV, label, inV, properties=None, labels=None):
+ if labels is not None and len(labels) > 0:
+ self._labels = set(labels)
+ Element.__init__(self, id, next(iter(labels)), properties)
+ else:
+ self._labels = {label} if label else {"edge"}
+ Element.__init__(self, id, label or "edge", properties)
self.outV = outV
self.inV = inV
+ @property
+ def labels(self):
+ return frozenset(self._labels)
+
def __repr__(self):
return "e[" + str(self.id) + "][" + str(self.outV.id) + "-" + self.label + "->" + str(self.inV.id) + "]"
diff --git a/gremlin-python/src/main/python/gremlin_python/structure/io/graphbinaryV4.py b/gremlin-python/src/main/python/gremlin_python/structure/io/graphbinaryV4.py
index 41843a33eb..59a159fc39 100644
--- a/gremlin-python/src/main/python/gremlin_python/structure/io/graphbinaryV4.py
+++ b/gremlin-python/src/main/python/gremlin_python/structure/io/graphbinaryV4.py
@@ -593,12 +593,21 @@ class EdgeIO(_GraphBinaryTypeIO):
cls.prefix_bytes(cls.graphbinary_type, as_value, nullable, to_extend)
writer.to_dict(obj.id, to_extend)
- # serializing label as list here for now according to GraphBinaryV4
- ListIO.dictify([obj.label], writer, to_extend, True, False)
+ # serializing labels as list according to GraphBinaryV4
+ if hasattr(obj, '_labels') and obj._labels:
+ ListIO.dictify(list(obj._labels), writer, to_extend, True, False)
+ else:
+ ListIO.dictify([obj.label], writer, to_extend, True, False)
writer.to_dict(obj.inV.id, to_extend)
- ListIO.dictify([obj.inV.label], writer, to_extend, True, False)
+ if hasattr(obj.inV, '_labels') and obj.inV._labels:
+ ListIO.dictify(list(obj.inV._labels), writer, to_extend, True, False)
+ else:
+ ListIO.dictify([obj.inV.label], writer, to_extend, True, False)
writer.to_dict(obj.outV.id, to_extend)
- ListIO.dictify([obj.outV.label], writer, to_extend, True, False)
+ if hasattr(obj.outV, '_labels') and obj.outV._labels:
+ ListIO.dictify(list(obj.outV._labels), writer, to_extend, True, False)
+ else:
+ ListIO.dictify([obj.outV.label], writer, to_extend, True, False)
to_extend.extend(NULL_BYTES)
to_extend.extend(NULL_BYTES)
@@ -611,15 +620,15 @@ class EdgeIO(_GraphBinaryTypeIO):
@classmethod
def _read_edge(cls, b, r):
edgeid = r.read_object(b)
- # reading single string value for now according to GraphBinaryV4
- edgelbl = r.to_object(b, DataType.list, False)[0]
+ # reading label list according to GraphBinaryV4
+ edge_labels = r.to_object(b, DataType.list, False)
inv = Vertex(r.read_object(b), r.to_object(b, DataType.list, False)[0])
outv = Vertex(r.read_object(b), r.to_object(b, DataType.list, False)[0])
b.read(2)
props = r.read_object(b)
# null properties are returned as empty lists
properties = [] if props is None else props
- edge = Edge(edgeid, outv, edgelbl, inv, properties)
+ edge = Edge(edgeid, outv, edge_labels[0] if edge_labels else "edge", inv, properties, labels=edge_labels)
return edge
@@ -679,7 +688,10 @@ class TinkerGraphIO(_GraphBinaryTypeIO):
IntIO.dictify(len(vertices), writer, to_extend, True, False)
for v in vertices:
writer.to_dict(v.id, to_extend)
- ListIO.dictify([v.label], writer, to_extend, True, False)
+ if hasattr(v, '_labels') and v._labels:
+ ListIO.dictify(list(v._labels), writer, to_extend, True, False)
+ else:
+ ListIO.dictify([v.label], writer, to_extend, True, False)
v_props = v.properties
IntIO.dictify(len(v_props), writer, to_extend, True, False)
for vp in v_props:
@@ -692,7 +704,10 @@ class TinkerGraphIO(_GraphBinaryTypeIO):
IntIO.dictify(len(edges), writer, to_extend, True, False)
for e in edges:
writer.to_dict(e.id, to_extend)
- ListIO.dictify([e.label], writer, to_extend, True, False)
+ if hasattr(e, '_labels') and e._labels:
+ ListIO.dictify(list(e._labels), writer, to_extend, True, False)
+ else:
+ ListIO.dictify([e.label], writer, to_extend, True, False)
writer.to_dict(e.inV.id, to_extend)
writer.to_dict(None, to_extend)
writer.to_dict(e.outV.id, to_extend)
@@ -712,8 +727,8 @@ class TinkerGraphIO(_GraphBinaryTypeIO):
vertex_count = r.to_object(b, DataType.int, False)
for _ in range(vertex_count):
v_id = r.read_object(b)
- v_label = r.to_object(b, DataType.list, False)[0]
- vertex = Vertex(v_id, v_label)
+ v_labels = r.to_object(b, DataType.list, False)
+ vertex = Vertex(v_id, v_labels[0] if v_labels else "vertex", labels=v_labels)
graph.vertices[v_id] = vertex
vp_count = r.to_object(b, DataType.int, False)
@@ -732,14 +747,15 @@ class TinkerGraphIO(_GraphBinaryTypeIO):
edge_count = r.to_object(b, DataType.int, False)
for _ in range(edge_count):
e_id = r.read_object(b)
- e_label = r.to_object(b, DataType.list, False)[0]
+ e_labels = r.to_object(b, DataType.list, False)
in_v_id = r.read_object(b)
r.read_object(b) # discard in-v label
out_v_id = r.read_object(b)
r.read_object(b) # discard out-v label
r.read_object(b) # discard parent
- edge = Edge(e_id, graph.vertices[out_v_id], e_label, graph.vertices[in_v_id])
+ edge = Edge(e_id, graph.vertices[out_v_id], e_labels[0] if e_labels else "edge",
+ graph.vertices[in_v_id], labels=e_labels)
graph.edges[e_id] = edge
edge_props = r.to_object(b, DataType.list, False)
@@ -758,8 +774,11 @@ class VertexIO(_GraphBinaryTypeIO):
def dictify(cls, obj, writer, to_extend, as_value=False, nullable=True):
cls.prefix_bytes(cls.graphbinary_type, as_value, nullable, to_extend)
writer.to_dict(obj.id, to_extend)
- # serializing label as list here for now according to GraphBinaryV4
- ListIO.dictify([obj.label], writer, to_extend, True, False)
+ # serializing labels as list according to GraphBinaryV4
+ if hasattr(obj, '_labels') and obj._labels:
+ ListIO.dictify(list(obj._labels), writer, to_extend, True, False)
+ else:
+ ListIO.dictify([obj.label], writer, to_extend, True, False)
to_extend.extend(NULL_BYTES)
return to_extend
@@ -770,12 +789,12 @@ class VertexIO(_GraphBinaryTypeIO):
@classmethod
def _read_vertex(cls, b, r):
vertex_id = r.read_object(b)
- # reading single string value for now according to GraphBinaryV4
- vertex_label = r.to_object(b, DataType.list, False)[0]
+ # reading label list according to GraphBinaryV4
+ vertex_labels = r.to_object(b, DataType.list, False)
props = r.read_object(b)
# null properties are returned as empty lists
properties = [] if props is None else props
- vertex = Vertex(vertex_id, vertex_label, properties)
+ vertex = Vertex(vertex_id, vertex_labels[0] if vertex_labels else "vertex", properties, labels=vertex_labels)
return vertex
diff --git a/gremlin-python/src/main/python/tests/feature/gremlin.py b/gremlin-python/src/main/python/tests/feature/gremlin.py
index e111d52b73..ba27449594 100644
--- a/gremlin-python/src/main/python/tests/feature/gremlin.py
+++ b/gremlin-python/src/main/python/tests/feature/gremlin.py
@@ -931,6 +931,8 @@ world.gremlins = {
'g_V_limitX3X_addVXsoftwareX_aggregateXa1X_byXlabelX_aggregateXa2X_byXlabelX_capXa1_a2X_selectXa_bX_byXunfoldX_foldX': [(lambda g:g.add_v('person').property('name', 'marko').property('age', 29).as_('marko').add_v('person').property('name', 'vadas').property('age', 27).as_('vadas').add_v('software').property('name', 'lop').property('lang', 'java').as_('lop').add_v('person').property('name', 'josh').property('age', 32).as_('josh').add_v('software').property('name', 'ripple').property(' [...]
'g_addV_propertyXname_markoX_withXkey_valueX_valuesXname_keyX': [(lambda g:g.add_v().property('name', 'marko').with_('key', 'value').values('name', 'key'))],
'g_addV_propertyXname_marko_since_2010X_withXkey_valueX_propertiesXnameX_valuesXsince_keyX': [(lambda g:g.add_v().property('name', 'marko', 'since', 2010).with_('key', 'value').properties('name').values('since', 'key'))],
+ 'g_addVXa_bX_labels': [(lambda g:g.add_v('a', 'b').labels().fold()), (lambda g:g.V().has_label('a').has_label('b')), (lambda g:g.add_v('a', 'b')), (lambda g:g.V().labels())],
+ 'g_addVXa_b_cX_labels_count': [(lambda g:g.add_v('a', 'b', 'c').labels().count())],
'g_injectX1X_asBool': [(lambda g:g.inject(1).as_bool())],
'g_injectX3_14X_asBool': [(lambda g:g.inject(3.14).as_bool())],
'g_injectXneg_1X_asBool': [(lambda g:g.inject(-1).as_bool())],
@@ -1225,6 +1227,10 @@ world.gremlins = {
'g_injectXListX1_2XX_lTrimXlocalX': [(lambda g:g.inject([1, 2]).l_trim(Scope.local))],
'g_V_valuesXnameX_lTrim': [(lambda g:g.add_v('person').property('name', ' marko ').property('age', 29).as_('marko').add_v('person').property('name', ' vadas ').property('age', 27).as_('vadas').add_v('software').property('name', ' lop').property('lang', 'java').as_('lop').add_v('person').property('name', 'josh ').property('age', 32).as_('josh').add_v('software').property('name', ' ripple ').property('lang', 'java').as_('ripple').add_v('person').property('name', 'peter').proper [...]
'g_V_valuesXnameX_order_fold_lTrimXlocalX': [(lambda g:g.add_v('person').property('name', ' marko ').property('age', 29).as_('marko').add_v('person').property('name', ' vadas ').property('age', 27).as_('vadas').add_v('software').property('name', ' lop').property('lang', 'java').as_('lop').add_v('person').property('name', 'josh ').property('age', 32).as_('josh').add_v('software').property('name', ' ripple ').property('lang', 'java').as_('ripple').add_v('person').property('name [...]
+ 'g_V_hasLabelXpersonX_labels': [(lambda g:g.V().has_label('person').labels())],
+ 'g_addVXa_bX_labels_count': [(lambda g:g.add_v('a', 'b')), (lambda g:g.V().labels().count())],
+ 'g_addV_labels': [(lambda g:g.add_v()), (lambda g:g.V().labels())],
+ 'g_E_labels': [(lambda g:g.E().has_label('knows').labels())],
'g_injectXfeature_test_nullX_length': [(lambda g:g.inject('feature', 'test', None).length())],
'g_injectXfeature_test_nullX_lengthXlocalX': [(lambda g:g.inject('feature', 'test', None).length(Scope.local))],
'g_injectXListXa_bXX_length': [(lambda g:g.inject(['a', 'b']).length())],
@@ -1491,6 +1497,15 @@ world.gremlins = {
'g_mergeV_hidden_label_key_onMatch_matched_prohibited': [(lambda g, xx1=None:g.merge_v({ }).option(Merge.on_match, xx1))],
'g_injectXlist1_list2_list3X_fold_asXmX_mergeVXselectXmX_limitXlocal_1X_unfoldX_optionXonCreate_selectXmX_rangeXlocal_1_2X_unfoldX_optionXonMatch_selectXmX_tailXlocalX_unfoldX_to_match': [(lambda g:g.add_v('person').property('name', 'marko').property('age', 29)), (lambda g:g.inject({ T.label: 'person', 'name': 'marko' }, { T.label: 'person', 'name': 'marko' }, { 'created': 'N' }).fold().as_('m').merge_v(__.select('m').limit(Scope.local, 1).unfold()).option(Merge.on_create, __.select( [...]
'g_injectXlist1_list2_list3X_fold_asXmX_mergeVXselectXmX_limitXlocal_1X_unfoldX_optionXonCreate_selectXmX_rangeXlocal_1_2X_unfoldX_optionXonMatch_selectXmX_tailXlocalX_unfoldX_to_create': [(lambda g:g.add_v('person').property('name', 'marko').property('age', 29)), (lambda g:g.inject({ T.label: 'person', 'name': 'stephen' }, { T.label: 'person', 'name': 'stephen' }, { 'created': 'N' }).fold().as_('m').merge_v(__.select('m').limit(Scope.local, 1).unfold()).option(Merge.on_create, __.se [...]
+ 'g_mergeVXlabel_ab_name_markoX_multilabel_create': [(lambda g:g.merge_v({ T.label: ['person', 'employee'], 'name': 'marko' })), (lambda g:g.V()), (lambda g:g.V().has_label('person').has_label('employee')), (lambda g:g.V().has('name', 'marko'))],
+ 'g_mergeVXlabel_abc_name_testX_multilabel_create': [(lambda g:g.merge_v({ T.label: ['a', 'b', 'c'], 'name': 'test' })), (lambda g:g.V()), (lambda g:g.V().has_label('a').has_label('b').has_label('c'))],
+ 'g_mergeVXlabel_ab_name_markoX_multilabel_match': [(lambda g:g.add_v('person').add_label('employee').property('name', 'marko')), (lambda g:g.merge_v({ T.label: ['person', 'employee'], 'name': 'marko' })), (lambda g:g.V()), (lambda g:g.V().has_label('person').has_label('employee'))],
+ 'g_mergeVXlabel_ab_name_markoX_multilabel_nomatch': [(lambda g:g.add_v('person').property('name', 'marko')), (lambda g:g.merge_v({ T.label: ['person', 'employee'], 'name': 'marko' })), (lambda g:g.V())],
+ 'g_mergeVXlabel_person_name_markoX_optionXonMatch_label_managerX': [(lambda g:g.add_v('person').add_label('employee').property('name', 'marko')), (lambda g:g.merge_v({ T.label: 'person', 'name': 'marko' }).option(Merge.on_match, { T.label: 'manager' })), (lambda g:g.V()), (lambda g:g.V().has_label('manager')), (lambda g:g.V().has_label('person')), (lambda g:g.V().has_label('employee'))],
+ 'g_mergeVXlabel_person_name_markoX_optionXonMatch_label_manager_directorX': [(lambda g:g.add_v('person').property('name', 'marko')), (lambda g:g.merge_v({ T.label: 'person', 'name': 'marko' }).option(Merge.on_match, { T.label: ['manager', 'director'] })), (lambda g:g.V()), (lambda g:g.V().has_label('manager').has_label('director')), (lambda g:g.V().has_label('person'))],
+ 'g_mergeVXlabel_person_name_markoX_optionXonMatch_label_emptyX': [(lambda g:g.add_v('person').property('name', 'marko')), (lambda g:g.merge_v({ T.label: 'person', 'name': 'marko' }).option(Merge.on_match, { T.label: [] })), (lambda g:g.V()), (lambda g:g.V().has_label('person'))],
+ 'g_mergeVXname_markoX_optionXonCreate_label_ab_name_markoX': [(lambda g:g.merge_v({ 'name': 'marko' }).option(Merge.on_create, { T.label: ['person', 'employee'], 'name': 'marko' })), (lambda g:g.V()), (lambda g:g.V().has_label('person').has_label('employee')), (lambda g:g.V().has('name', 'marko'))],
+ 'g_mergeVXlabel_person_name_markoX_optionXonMatch_label_existingX': [(lambda g:g.add_v('person').add_label('employee').property('name', 'marko')), (lambda g:g.merge_v({ T.label: 'person', 'name': 'marko' }).option(Merge.on_match, { T.label: 'person' })), (lambda g:g.V()), (lambda g:g.V().has_label('person').has_label('employee'))],
'g_V_age_min': [(lambda g:g.V().values('age').min_())],
'g_V_foo_min': [(lambda g:g.V().values('foo').min_())],
'g_V_name_min': [(lambda g:g.V().values('name').min_())],
@@ -1976,6 +1991,10 @@ world.gremlins = {
'g_V_out_out_properties_asXheadX_path_order_byXdescX_selectXheadX_value': [(lambda g:g.V().out().out().properties().as_('head').path().order().by(Order.desc).select('head').value())],
'g_V_out_out_values_asXheadX_path_order_byXascX_selectXheadX': [(lambda g:g.V().out().out().values().as_('head').path().order().by(Order.asc).select('head'))],
'g_V_out_out_values_asXheadX_path_order_byXdescX_selectXheadX': [(lambda g:g.V().out().out().values().as_('head').path().order().by(Order.desc).select('head'))],
+ 'g_V_hasLabelXpersonX_hasXname_markoX_addLabelXemployeeX_labels': [(lambda g:g.add_v('person').property('name', 'marko')), (lambda g:g.V().has_label('person').has('name', 'marko').add_label('employee').labels().fold()), (lambda g:g.V().has_label('person').has_label('employee'))],
+ 'g_V_addLabelXa_bX_labels_count': [(lambda g:g.add_v('person')), (lambda g:g.V().add_label('a', 'b').labels().count())],
+ 'g_V_addLabelXexistingX_labels_count': [(lambda g:g.add_v('person')), (lambda g:g.V().add_label('person').labels().count())],
+ 'g_E_addLabelXfriendX_labels_fold': [(lambda g:g.add_v('person').property('name', 'marko').as_('a').add_v('person').property('name', 'josh').as_('b').add_e('knows').from_('a').to('b')), (lambda g:g.E().add_label('friend').labels().fold())],
'g_V_valueXnameX_aggregateXxX_capXxX': [(lambda g:g.V().values('name').aggregate('x').cap('x'))],
'g_V_aggregateXxX_byXnameX_capXxX': [(lambda g:g.V().aggregate('x').by('name').cap('x'))],
'g_V_out_aggregateXaX_path': [(lambda g:g.V().out().aggregate('a').path())],
@@ -2033,6 +2052,13 @@ world.gremlins = {
'g_V_repeatXaggregateXaXX_timesX2X_capXaX_unfold': [(lambda g:g.V().repeat(__.aggregate('a')).times(2).cap('a').unfold())],
'g_V_aggregateXaX_capXaX_unfold_both': [(lambda g:g.V().aggregate('a').cap('a').unfold().both())],
'g_V_aggregateXaX_capXaX_unfold_barrier_both': [(lambda g:g.V().aggregate('a').cap('a').unfold().barrier().both())],
+ 'g_V_dropLabelXaX_labels': [(lambda g:g.add_v('a', 'b')), (lambda g:g.V().drop_label('a').labels().fold()), (lambda g:g.V().has_label('a')), (lambda g:g.V().has_label('b'))],
+ 'g_V_dropLabels_labels': [(lambda g:g.add_v('a', 'b')), (lambda g:g.V().drop_labels().labels())],
+ 'g_V_dropLabelXa_bX_labels': [(lambda g:g.add_v('a', 'b', 'c')), (lambda g:g.V().drop_label('a', 'b').labels())],
+ 'g_V_dropLabels_defaultLabel': [(lambda g:g.add_v('person')), (lambda g:g.V().drop_labels().labels())],
+ 'g_E_dropLabelXknowsX_labels': [(lambda g:g.add_v('person').as_('a').add_v('person').as_('b').add_e('knows').from_('a').to('b')), (lambda g:g.E().drop_label('knows').labels().fold())],
+ 'g_E_dropLabels_labels': [(lambda g:g.add_v('person').as_('a').add_v('person').as_('b').add_e('knows').from_('a').to('b')), (lambda g:g.E().drop_labels().labels())],
+ 'g_V_dropLabelXnonExistentX_labels': [(lambda g:g.add_v('a', 'b')), (lambda g:g.V().drop_label('xyz').labels())],
'g_V_fail': [(lambda g:g.V().fail())],
'g_V_failXmsgX': [(lambda g:g.V().fail('msg'))],
'g_V_unionXout_failX': [(lambda g:g.V().union(__.out(), __.fail()))],
diff --git a/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/language/translator/translations.json b/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/language/translator/translations.json
index aaf373e313..338c567b7a 100644
--- a/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/language/translator/translations.json
+++ b/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/language/translator/translations.json
@@ -17831,6 +17831,88 @@
}
]
},
+ {
+ "scenario": "g_addEXa_bX_from_V_to_V_labels_fold",
+ "traversals": [
+ {
+ "original": "g.addV(\"person\").property(\"name\", \"marko\").addV(\"person\").property(\"name\", \"josh\")",
+ "language": "g.addV(\"person\").property(\"name\", \"marko\").addV(\"person\").property(\"name\", \"josh\")",
+ "canonical": "g.addV(\"person\").property(\"name\", \"marko\").addV(\"person\").property(\"name\", \"josh\")",
+ "anonymized": "g.addV(string0).property(string1, string2).addV(string0).property(string1, string3)",
+ "dotnet": "g.AddV((string) \"person\").Property(\"name\", \"marko\").AddV((string) \"person\").Property(\"name\", \"josh\")",
+ "go": "g.AddV(\"person\").Property(\"name\", \"marko\").AddV(\"person\").Property(\"name\", \"josh\")",
+ "groovy": "g.addV(\"person\").property(\"name\", \"marko\").addV(\"person\").property(\"name\", \"josh\")",
+ "java": "g.addV(\"person\").property(\"name\", \"marko\").addV(\"person\").property(\"name\", \"josh\")",
+ "javascript": "g.addV(\"person\").property(\"name\", \"marko\").addV(\"person\").property(\"name\", \"josh\")",
+ "python": "g.add_v('person').property('name', 'marko').add_v('person').property('name', 'josh')"
+ },
+ {
+ "original": "g.addE(\"knows\", \"trusts\").from(__.V().has(\"name\", \"marko\")).to(__.V().has(\"name\", \"josh\")).labels().fold()",
+ "language": "g.addE(\"knows\", \"trusts\").from(__.V().has(\"name\", \"marko\")).to(__.V().has(\"name\", \"josh\")).labels().fold()",
+ "canonical": "g.addE(\"knows\", \"trusts\").from(__.V().has(\"name\", \"marko\")).to(__.V().has(\"name\", \"josh\")).labels().fold()",
+ "anonymized": "g.addE(string0, string1).from(__.V().has(string2, string3)).to(__.V().has(string2, string4)).labels().fold()",
+ "dotnet": "g.AddE((string) \"knows\", (string) \"trusts\").From(__.V().Has(\"name\", \"marko\")).To(__.V().Has(\"name\", \"josh\")).Labels().Fold()",
+ "go": "g.AddE(\"knows\", \"trusts\").From(gremlingo.T__.V().Has(\"name\", \"marko\")).To(gremlingo.T__.V().Has(\"name\", \"josh\")).Labels().Fold()",
+ "groovy": "g.addE(\"knows\", \"trusts\").from(__.V().has(\"name\", \"marko\")).to(__.V().has(\"name\", \"josh\")).labels().fold()",
+ "java": "g.addE(\"knows\", \"trusts\").from(__.V().has(\"name\", \"marko\")).to(__.V().has(\"name\", \"josh\")).labels().fold()",
+ "javascript": "g.addE(\"knows\", \"trusts\").from_(__.V().has(\"name\", \"marko\")).to(__.V().has(\"name\", \"josh\")).labels().fold()",
+ "python": "g.add_e('knows', 'trusts').from_(__.V().has('name', 'marko')).to(__.V().has('name', 'josh')).labels().fold()"
+ },
+ {
+ "original": "g.E().hasLabel(\"knows\")",
+ "language": "g.E().hasLabel(\"knows\")",
+ "canonical": "g.E().hasLabel(\"knows\")",
+ "anonymized": "g.E().hasLabel(string0)",
+ "dotnet": "g.E().HasLabel(\"knows\")",
+ "go": "g.E().HasLabel(\"knows\")",
+ "groovy": "g.E().hasLabel(\"knows\")",
+ "java": "g.E().hasLabel(\"knows\")",
+ "javascript": "g.E().hasLabel(\"knows\")",
+ "python": "g.E().has_label('knows')"
+ },
+ {
+ "original": "g.E().hasLabel(\"trusts\")",
+ "language": "g.E().hasLabel(\"trusts\")",
+ "canonical": "g.E().hasLabel(\"trusts\")",
+ "anonymized": "g.E().hasLabel(string0)",
+ "dotnet": "g.E().HasLabel(\"trusts\")",
+ "go": "g.E().HasLabel(\"trusts\")",
+ "groovy": "g.E().hasLabel(\"trusts\")",
+ "java": "g.E().hasLabel(\"trusts\")",
+ "javascript": "g.E().hasLabel(\"trusts\")",
+ "python": "g.E().has_label('trusts')"
+ }
+ ]
+ },
+ {
+ "scenario": "g_addEXa_b_cX_from_V_to_V_labels_count",
+ "traversals": [
+ {
+ "original": "g.addV(\"person\").property(\"name\", \"marko\").addV(\"person\").property(\"name\", \"josh\")",
+ "language": "g.addV(\"person\").property(\"name\", \"marko\").addV(\"person\").property(\"name\", \"josh\")",
+ "canonical": "g.addV(\"person\").property(\"name\", \"marko\").addV(\"person\").property(\"name\", \"josh\")",
+ "anonymized": "g.addV(string0).property(string1, string2).addV(string0).property(string1, string3)",
+ "dotnet": "g.AddV((string) \"person\").Property(\"name\", \"marko\").AddV((string) \"person\").Property(\"name\", \"josh\")",
+ "go": "g.AddV(\"person\").Property(\"name\", \"marko\").AddV(\"person\").Property(\"name\", \"josh\")",
+ "groovy": "g.addV(\"person\").property(\"name\", \"marko\").addV(\"person\").property(\"name\", \"josh\")",
+ "java": "g.addV(\"person\").property(\"name\", \"marko\").addV(\"person\").property(\"name\", \"josh\")",
+ "javascript": "g.addV(\"person\").property(\"name\", \"marko\").addV(\"person\").property(\"name\", \"josh\")",
+ "python": "g.add_v('person').property('name', 'marko').add_v('person').property('name', 'josh')"
+ },
+ {
+ "original": "g.addE(\"a\", \"b\", \"c\").from(__.V().has(\"name\", \"marko\")).to(__.V().has(\"name\", \"josh\")).labels().count()",
+ "language": "g.addE(\"a\", \"b\", \"c\").from(__.V().has(\"name\", \"marko\")).to(__.V().has(\"name\", \"josh\")).labels().count()",
+ "canonical": "g.addE(\"a\", \"b\", \"c\").from(__.V().has(\"name\", \"marko\")).to(__.V().has(\"name\", \"josh\")).labels().count()",
+ "anonymized": "g.addE(string0, string1, string2).from(__.V().has(string3, string4)).to(__.V().has(string3, string5)).labels().count()",
+ "dotnet": "g.AddE((string) \"a\", (string) \"b\", (string) \"c\").From(__.V().Has(\"name\", \"marko\")).To(__.V().Has(\"name\", \"josh\")).Labels().Count()",
+ "go": "g.AddE(\"a\", \"b\", \"c\").From(gremlingo.T__.V().Has(\"name\", \"marko\")).To(gremlingo.T__.V().Has(\"name\", \"josh\")).Labels().Count()",
+ "groovy": "g.addE(\"a\", \"b\", \"c\").from(__.V().has(\"name\", \"marko\")).to(__.V().has(\"name\", \"josh\")).labels().count()",
+ "java": "g.addE(\"a\", \"b\", \"c\").from(__.V().has(\"name\", \"marko\")).to(__.V().has(\"name\", \"josh\")).labels().count()",
+ "javascript": "g.addE(\"a\", \"b\", \"c\").from_(__.V().has(\"name\", \"marko\")).to(__.V().has(\"name\", \"josh\")).labels().count()",
+ "python": "g.add_e('a', 'b', 'c').from_(__.V().has('name', 'marko')).to(__.V().has('name', 'josh')).labels().count()"
+ }
+ ]
+ },
{
"scenario": "g_VX1X_addVXanimalX_propertyXage_selectXaX_byXageXX_propertyXname_puppyX",
"traversals": [
@@ -41969,6 +42051,59 @@
}
]
},
+ {
+ "scenario": "g_E_addLabelXfriendX_labels_fold",
+ "traversals": [
+ {
+ "original": "g.addV(\"person\").property(\"name\", \"marko\").as(\"a\").addV(\"person\").property(\"name\", \"josh\").as(\"b\").addE(\"knows\").from(\"a\").to(\"b\")",
+ "language": "g.addV(\"person\").property(\"name\", \"marko\").as(\"a\").addV(\"person\").property(\"name\", \"josh\").as(\"b\").addE(\"knows\").from(\"a\").to(\"b\")",
+ "canonical": "g.addV(\"person\").property(\"name\", \"marko\").as(\"a\").addV(\"person\").property(\"name\", \"josh\").as(\"b\").addE(\"knows\").from(\"a\").to(\"b\")",
+ "anonymized": "g.addV(string0).property(string1, string2).as(string3).addV(string0).property(string1, string4).as(string5).addE(string6).from(string3).to(string5)",
+ "dotnet": "g.AddV((string) \"person\").Property(\"name\", \"marko\").As(\"a\").AddV((string) \"person\").Property(\"name\", \"josh\").As(\"b\").AddE((string) \"knows\").From(\"a\").To(\"b\")",
+ "go": "g.AddV(\"person\").Property(\"name\", \"marko\").As(\"a\").AddV(\"person\").Property(\"name\", \"josh\").As(\"b\").AddE(\"knows\").From(\"a\").To(\"b\")",
+ "groovy": "g.addV(\"person\").property(\"name\", \"marko\").as(\"a\").addV(\"person\").property(\"name\", \"josh\").as(\"b\").addE(\"knows\").from(\"a\").to(\"b\")",
+ "java": "g.addV(\"person\").property(\"name\", \"marko\").as(\"a\").addV(\"person\").property(\"name\", \"josh\").as(\"b\").addE(\"knows\").from(\"a\").to(\"b\")",
+ "javascript": "g.addV(\"person\").property(\"name\", \"marko\").as(\"a\").addV(\"person\").property(\"name\", \"josh\").as(\"b\").addE(\"knows\").from_(\"a\").to(\"b\")",
+ "python": "g.add_v('person').property('name', 'marko').as_('a').add_v('person').property('name', 'josh').as_('b').add_e('knows').from_('a').to('b')"
+ },
+ {
+ "original": "g.E().addLabel(\"friend\").labels().fold()",
+ "language": "g.E().addLabel(\"friend\").labels().fold()",
+ "canonical": "g.E().addLabel(\"friend\").labels().fold()",
+ "anonymized": "g.E().addLabel(string0).labels().fold()",
+ "dotnet": "g.E().AddLabel(\"friend\").Labels().Fold()",
+ "go": "g.E().AddLabel(\"friend\").Labels().Fold()",
+ "groovy": "g.E().addLabel(\"friend\").labels().fold()",
+ "java": "g.E().addLabel(\"friend\").labels().fold()",
+ "javascript": "g.E().addLabel(\"friend\").labels().fold()",
+ "python": "g.E().add_label('friend').labels().fold()"
+ },
+ {
+ "original": "g.E().hasLabel(\"knows\")",
+ "language": "g.E().hasLabel(\"knows\")",
+ "canonical": "g.E().hasLabel(\"knows\")",
+ "anonymized": "g.E().hasLabel(string0)",
+ "dotnet": "g.E().HasLabel(\"knows\")",
+ "go": "g.E().HasLabel(\"knows\")",
+ "groovy": "g.E().hasLabel(\"knows\")",
+ "java": "g.E().hasLabel(\"knows\")",
+ "javascript": "g.E().hasLabel(\"knows\")",
+ "python": "g.E().has_label('knows')"
+ },
+ {
+ "original": "g.E().hasLabel(\"friend\")",
+ "language": "g.E().hasLabel(\"friend\")",
+ "canonical": "g.E().hasLabel(\"friend\")",
+ "anonymized": "g.E().hasLabel(string0)",
+ "dotnet": "g.E().HasLabel(\"friend\")",
+ "go": "g.E().HasLabel(\"friend\")",
+ "groovy": "g.E().hasLabel(\"friend\")",
+ "java": "g.E().hasLabel(\"friend\")",
+ "javascript": "g.E().hasLabel(\"friend\")",
+ "python": "g.E().has_label('friend')"
+ }
+ ]
+ },
{
"scenario": "g_V_valueXnameX_aggregateXxX_capXxX",
"traversals": [
@@ -43078,6 +43213,88 @@
}
]
},
+ {
+ "scenario": "g_E_dropLabelXknowsX_labels",
+ "traversals": [
+ {
+ "original": "g.addV(\"person\").as(\"a\").addV(\"person\").as(\"b\").addE(\"knows\", \"trusts\").from(\"a\").to(\"b\")",
+ "language": "g.addV(\"person\").as(\"a\").addV(\"person\").as(\"b\").addE(\"knows\", \"trusts\").from(\"a\").to(\"b\")",
+ "canonical": "g.addV(\"person\").as(\"a\").addV(\"person\").as(\"b\").addE(\"knows\", \"trusts\").from(\"a\").to(\"b\")",
+ "anonymized": "g.addV(string0).as(string1).addV(string0).as(string2).addE(string3, string4).from(string1).to(string2)",
+ "dotnet": "g.AddV((string) \"person\").As(\"a\").AddV((string) \"person\").As(\"b\").AddE(\"knows\", \"trusts\").From(\"a\").To(\"b\")",
+ "go": "g.AddV(\"person\").As(\"a\").AddV(\"person\").As(\"b\").AddE(\"knows\", \"trusts\").From(\"a\").To(\"b\")",
+ "groovy": "g.addV(\"person\").as(\"a\").addV(\"person\").as(\"b\").addE(\"knows\", \"trusts\").from(\"a\").to(\"b\")",
+ "java": "g.addV(\"person\").as(\"a\").addV(\"person\").as(\"b\").addE(\"knows\", \"trusts\").from(\"a\").to(\"b\")",
+ "javascript": "g.addV(\"person\").as(\"a\").addV(\"person\").as(\"b\").addE(\"knows\", \"trusts\").from_(\"a\").to(\"b\")",
+ "python": "g.add_v('person').as_('a').add_v('person').as_('b').add_e('knows', 'trusts').from_('a').to('b')"
+ },
+ {
+ "original": "g.E().dropLabel(\"knows\").labels().fold()",
+ "language": "g.E().dropLabel(\"knows\").labels().fold()",
+ "canonical": "g.E().dropLabel(\"knows\").labels().fold()",
+ "anonymized": "g.E().dropLabel(string0).labels().fold()",
+ "dotnet": "g.E().DropLabel(\"knows\").Labels().Fold()",
+ "go": "g.E().DropLabel(\"knows\").Labels().Fold()",
+ "groovy": "g.E().dropLabel(\"knows\").labels().fold()",
+ "java": "g.E().dropLabel(\"knows\").labels().fold()",
+ "javascript": "g.E().dropLabel(\"knows\").labels().fold()",
+ "python": "g.E().drop_label('knows').labels().fold()"
+ },
+ {
+ "original": "g.E().hasLabel(\"knows\")",
+ "language": "g.E().hasLabel(\"knows\")",
+ "canonical": "g.E().hasLabel(\"knows\")",
+ "anonymized": "g.E().hasLabel(string0)",
+ "dotnet": "g.E().HasLabel(\"knows\")",
+ "go": "g.E().HasLabel(\"knows\")",
+ "groovy": "g.E().hasLabel(\"knows\")",
+ "java": "g.E().hasLabel(\"knows\")",
+ "javascript": "g.E().hasLabel(\"knows\")",
+ "python": "g.E().has_label('knows')"
+ },
+ {
+ "original": "g.E().hasLabel(\"trusts\")",
+ "language": "g.E().hasLabel(\"trusts\")",
+ "canonical": "g.E().hasLabel(\"trusts\")",
+ "anonymized": "g.E().hasLabel(string0)",
+ "dotnet": "g.E().HasLabel(\"trusts\")",
+ "go": "g.E().HasLabel(\"trusts\")",
+ "groovy": "g.E().hasLabel(\"trusts\")",
+ "java": "g.E().hasLabel(\"trusts\")",
+ "javascript": "g.E().hasLabel(\"trusts\")",
+ "python": "g.E().has_label('trusts')"
+ }
+ ]
+ },
+ {
+ "scenario": "g_E_dropLabels_labels",
+ "traversals": [
+ {
+ "original": "g.addV(\"person\").as(\"a\").addV(\"person\").as(\"b\").addE(\"knows\", \"trusts\").from(\"a\").to(\"b\")",
+ "language": "g.addV(\"person\").as(\"a\").addV(\"person\").as(\"b\").addE(\"knows\", \"trusts\").from(\"a\").to(\"b\")",
+ "canonical": "g.addV(\"person\").as(\"a\").addV(\"person\").as(\"b\").addE(\"knows\", \"trusts\").from(\"a\").to(\"b\")",
+ "anonymized": "g.addV(string0).as(string1).addV(string0).as(string2).addE(string3, string4).from(string1).to(string2)",
+ "dotnet": "g.AddV((string) \"person\").As(\"a\").AddV((string) \"person\").As(\"b\").AddE(\"knows\", \"trusts\").From(\"a\").To(\"b\")",
+ "go": "g.AddV(\"person\").As(\"a\").AddV(\"person\").As(\"b\").AddE(\"knows\", \"trusts\").From(\"a\").To(\"b\")",
+ "groovy": "g.addV(\"person\").as(\"a\").addV(\"person\").as(\"b\").addE(\"knows\", \"trusts\").from(\"a\").to(\"b\")",
+ "java": "g.addV(\"person\").as(\"a\").addV(\"person\").as(\"b\").addE(\"knows\", \"trusts\").from(\"a\").to(\"b\")",
+ "javascript": "g.addV(\"person\").as(\"a\").addV(\"person\").as(\"b\").addE(\"knows\", \"trusts\").from_(\"a\").to(\"b\")",
+ "python": "g.add_v('person').as_('a').add_v('person').as_('b').add_e('knows', 'trusts').from_('a').to('b')"
+ },
+ {
+ "original": "g.E().dropLabels().labels()",
+ "language": "g.E().dropLabels().labels()",
+ "canonical": "g.E().dropLabels().labels()",
+ "anonymized": "g.E().dropLabels().labels()",
+ "dotnet": "g.E().DropLabels().Labels()",
+ "go": "g.E().DropLabels().Labels()",
+ "groovy": "g.E().dropLabels().labels()",
+ "java": "g.E().dropLabels().labels()",
+ "javascript": "g.E().dropLabels().labels()",
+ "python": "g.E().drop_labels().labels()"
+ }
+ ]
+ },
{
"scenario": "g_V_fail",
"traversals": [
diff --git a/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/test/features/map/AddEdge.feature b/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/test/features/map/AddEdge.feature
index 02c2be3d7b..267cefaec9 100644
--- a/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/test/features/map/AddEdge.feature
+++ b/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/test/features/map/AddEdge.feature
@@ -528,4 +528,36 @@ Feature: Step - addE()
addE("knows").from(__.V().has("name","marko"))
"""
When iterated to list
- Then the traversal will raise an error with message containing text of "must resolve to a Vertex or the ID of a Vertex present in the graph"
\ No newline at end of file
+ Then the traversal will raise an error with message containing text of "must resolve to a Vertex or the ID of a Vertex present in the graph"
+
+ @MultiLabel
+ Scenario: g_addEXa_bX_from_V_to_V_labels_fold
+ Given the empty graph
+ And the graph initializer of
+ """
+ g.addV("person").property("name", "marko").addV("person").property("name", "josh")
+ """
+ And the traversal of
+ """
+ g.addE("knows", "trusts").from(__.V().has("name", "marko")).to(__.V().has("name", "josh")).labels().fold()
+ """
+ When iterated to list
+ Then the result should have a count of 1
+ And the graph should return 1 for count of "g.E().hasLabel(\"knows\")"
+ And the graph should return 1 for count of "g.E().hasLabel(\"trusts\")"
+
+ @MultiLabel
+ Scenario: g_addEXa_b_cX_from_V_to_V_labels_count
+ Given the empty graph
+ And the graph initializer of
+ """
+ g.addV("person").property("name", "marko").addV("person").property("name", "josh")
+ """
+ And the traversal of
+ """
+ g.addE("a", "b", "c").from(__.V().has("name", "marko")).to(__.V().has("name", "josh")).labels().count()
+ """
+ When iterated to list
+ Then the result should be unordered
+ | result |
+ | d[3].l |
diff --git a/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/test/features/map/MergeEdge.feature b/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/test/features/map/MergeEdge.feature
index 6ffb7da16d..0513f5451d 100644
--- a/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/test/features/map/MergeEdge.feature
+++ b/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/test/features/map/MergeEdge.feature
@@ -1108,4 +1108,6 @@ Feature: Step - mergeE()
Then the result should have a count of 1
And the graph should return 2 for count of "g.V()"
And the graph should return 1 for count of "g.E().hasLabel(\"knows\")"
- And the graph should return 0 for count of "g.E().hasLabel(\"knows\").has(\"weight\")"
\ No newline at end of file
+ And the graph should return 0 for count of "g.E().hasLabel(\"knows\").has(\"weight\")"
+
+
diff --git a/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/test/features/sideEffect/AddLabel.feature b/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/test/features/sideEffect/AddLabel.feature
index 821b80ab72..5c0891ebb8 100644
--- a/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/test/features/sideEffect/AddLabel.feature
+++ b/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/test/features/sideEffect/AddLabel.feature
@@ -64,3 +64,19 @@ Feature: Step - addLabel()
Then the result should be unordered
| result |
| d[1].l |
+
+ @MultiLabel
+ Scenario: g_E_addLabelXfriendX_labels_fold
+ Given the empty graph
+ And the graph initializer of
+ """
+ g.addV("person").property("name", "marko").as("a").addV("person").property("name", "josh").as("b").addE("knows").from("a").to("b")
+ """
+ And the traversal of
+ """
+ g.E().addLabel("friend").labels().fold()
+ """
+ When iterated to list
+ Then the result should have a count of 1
+ And the graph should return 1 for count of "g.E().hasLabel(\"knows\")"
+ And the graph should return 1 for count of "g.E().hasLabel(\"friend\")"
diff --git a/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/test/features/sideEffect/DropLabel.feature b/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/test/features/sideEffect/DropLabel.feature
index 051cc793af..0c60f6c3c0 100644
--- a/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/test/features/sideEffect/DropLabel.feature
+++ b/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/test/features/sideEffect/DropLabel.feature
@@ -81,3 +81,35 @@ Feature: Step - dropLabel() / dropLabels()
Then the result should be unordered
| result |
| vertex |
+
+ @MultiLabel
+ Scenario: g_E_dropLabelXknowsX_labels
+ Given the empty graph
+ And the graph initializer of
+ """
+ g.addV("person").as("a").addV("person").as("b").addE("knows", "trusts").from("a").to("b")
+ """
+ And the traversal of
+ """
+ g.E().dropLabel("knows").labels().fold()
+ """
+ When iterated to list
+ Then the result should have a count of 1
+ And the graph should return 0 for count of "g.E().hasLabel(\"knows\")"
+ And the graph should return 1 for count of "g.E().hasLabel(\"trusts\")"
+
+ @MultiLabel
+ Scenario: g_E_dropLabels_labels
+ Given the empty graph
+ And the graph initializer of
+ """
+ g.addV("person").as("a").addV("person").as("b").addE("knows", "trusts").from("a").to("b")
+ """
+ And the traversal of
+ """
+ g.E().dropLabels().labels()
+ """
+ When iterated to list
+ Then the result should be unordered
+ | result |
+ | edge |
diff --git a/gremlin-util/src/test/java/org/apache/tinkerpop/gremlin/util/ser/binary/TypeSerializerFailureTests.java b/gremlin-util/src/test/java/org/apache/tinkerpop/gremlin/util/ser/binary/TypeSerializerFailureTests.java
index 3a9c816a0c..ad6e18d6bc 100644
--- a/gremlin-util/src/test/java/org/apache/tinkerpop/gremlin/util/ser/binary/TypeSerializerFailureTests.java
+++ b/gremlin-util/src/test/java/org/apache/tinkerpop/gremlin/util/ser/binary/TypeSerializerFailureTests.java
@@ -72,7 +72,7 @@ public class TypeSerializerFailureTests {
vertex,
bulkSet,
Collections.singletonList(vertex),
- new ReferenceEdge("an edge", null, vertex, vertex),
+ new ReferenceEdge("an edge", (String) null, vertex, vertex),
Lambda.supplier(null),
metrics,
new DefaultTraversalMetrics(1L, Collections.singletonList(metrics)),
diff --git a/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerEdge.java b/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerEdge.java
index 663908af0e..b37913a0aa 100644
--- a/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerEdge.java
+++ b/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerEdge.java
@@ -86,7 +86,7 @@ public class TinkerEdge extends TinkerElement implements Edge {
private TinkerEdge(final Object id, AbstractTinkerGraph graph, final Object outVertexId, final String label, final Object inVertexId, final long currentVersion, final Boolean skipIndexUpdate) {
super(id, label, currentVersion);
- this.edgeLabels = ConcurrentHashMap.newKeySet();
+ this.edgeLabels = new LinkedHashSet<>();
this.edgeLabels.add(label);
isTxMode = graph instanceof TinkerTransactionGraph;
this.graph = graph;
diff --git a/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerVertex.java b/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerVertex.java
index 457db2cc94..f3a97beb13 100644
--- a/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerVertex.java
+++ b/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerVertex.java
@@ -83,12 +83,9 @@ public class TinkerVertex extends TinkerElement implements Vertex {
this.graph = graph;
this.isTxMode = graph instanceof TinkerTransactionGraph;
this.allowNullPropertyValues = graph.features().vertex().supportsNullPropertyValues();
- this.vertexLabels = ConcurrentHashMap.newKeySet();
- if (labels == null || labels.isEmpty()) {
- this.vertexLabels.add(Vertex.DEFAULT_LABEL);
- } else {
- this.vertexLabels.addAll(labels);
- }
+ this.vertexLabels = (labels == null || labels.isEmpty())
+ ? new LinkedHashSet<>(Collections.singleton(Vertex.DEFAULT_LABEL))
+ : new LinkedHashSet<>(labels);
}
@Override
(tinkerpop) 05/05: Make TinkerGraph default to ONE for labels, add docs and changelog
Posted by xi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
xiazcy pushed a commit to branch multi-label-experiment
in repository https://gitbox.apache.org/repos/asf/tinkerpop.git
commit a37c5893c30ea50ef6571d84f7880d34cfa95966
Author: Yang Xia <xi...@gmail.com>
AuthorDate: Thu Jun 25 02:19:04 2026 -0700
Make TinkerGraph default to ONE for labels, add docs and changelog
- TinkerGraph defaults to LabelCardinality.ONE (backward-compatible)
- Add tinkergraph-multilabel.properties for multi-label graph configuration
- Add LabelsDropVerificationStrategy to prevent accidental labels().drop()
- Add multi-label TinkerGraph to Gremlin Server integration test config
- Update GLV Gherkin infrastructure to support multi-label test graph
- Add LabelCardinalityTest for verifying cardinality behavior
- Add feature tests: drop non-existent label, mergeV onCreate/onMatch
- Add unit tests: null/empty args, hasLabel OR/AND, index re-add cycle
- Add reference documentation for addLabel, dropLabel, labels steps
- Add upgrade documentation for users and providers
- Add provider semantics documentation
- Add CHANGELOG entries
---
CHANGELOG.asciidoc | 7 +
.../gremlin-server/gremlin-server-integration.yaml | 3 +
docs/src/dev/provider/gremlin-semantics.asciidoc | 86 +
.../reference/implementations-tinkergraph.asciidoc | 26 +
docs/src/reference/the-traversal.asciidoc | 126 +
docs/src/upgrade/release-4.x.x.asciidoc | 3469 ++++++++++----------
.../process/traversal/TraversalStrategies.java | 3 +
.../step/map/AbstractAddVertexStepPlaceholder.java | 6 +
.../traversal/step/map/AddVertexStartStep.java | 15 +-
.../step/map/AddVertexStartStepPlaceholder.java | 13 +-
.../LabelsDropVerificationStrategy.java | 66 +
.../apache/tinkerpop/gremlin/structure/Graph.java | 23 +-
.../structure/util/detached/DetachedVertex.java | 2 +-
.../LabelsDropVerificationStrategyTest.java | 85 +
.../Gherkin/CommonSteps.cs | 30 +-
.../Gherkin/GherkinTestRunner.cs | 6 -
.../Gremlin.Net.IntegrationTest/Gherkin/Gremlin.cs | 5 +-
.../Gherkin/IgnoreException.cs | 7 +-
.../Gherkin/ScenarioData.cs | 18 +
gremlin-go/driver/cucumber/cucumberSteps_test.go | 25 +-
gremlin-go/driver/cucumber/cucumberWorld.go | 22 +-
gremlin-go/driver/cucumber/gremlin.go | 5 +-
.../test/cucumber/feature-steps.js | 17 +-
.../gremlin-javascript/test/cucumber/gremlin.js | 5 +-
.../gremlin-javascript/test/cucumber/world.js | 27 +-
.../src/main/python/tests/feature/feature_steps.py | 21 +-
.../src/main/python/tests/feature/gremlin.py | 5 +-
.../src/main/python/tests/feature/terrain.py | 10 +
.../conf/tinkergraph-multilabel.properties | 21 +
.../gremlin/driver/remote/RemoteWorld.java | 18 +
.../server/util/CheckedGraphManagerTest.java | 2 +-
.../server/util/DefaultGraphManagerTest.java | 10 +-
.../gremlin/server/gremlin-server-integration.yaml | 3 +
.../test/scripts/tinkergraph-multilabel.properties | 21 +
.../tinkerpop/gremlin/features/StepDefinition.java | 14 +-
.../apache/tinkerpop/gremlin/features/World.java | 12 +
.../gremlin/language/translator/translations.json | 217 +-
.../gremlin/test/features/map/Labels.feature | 18 +-
.../gremlin/test/features/map/MergeVertex.feature | 44 +-
.../test/features/sideEffect/AddLabel.feature | 2 +-
.../test/features/sideEffect/DropLabel.feature | 21 +-
.../tinkergraph/structure/AbstractTinkerGraph.java | 11 -
.../gremlin/tinkergraph/structure/TinkerGraph.java | 19 +-
.../structure/TinkerTransactionGraph.java | 8 +-
.../tinkerpop/gremlin/tinkergraph/TinkerWorld.java | 1 +
.../process/traversal/step/map/LabelsStepTest.java | 25 +-
.../structure/LabelCardinalityTest.java | 318 ++
.../TinkerVertexMultiLabelGremlinLangTest.java | 20 +-
48 files changed, 2998 insertions(+), 1940 deletions(-)
diff --git a/CHANGELOG.asciidoc b/CHANGELOG.asciidoc
index 0fe949254e..c5a2347189 100644
--- a/CHANGELOG.asciidoc
+++ b/CHANGELOG.asciidoc
@@ -30,6 +30,13 @@ image::https://raw.githubusercontent.com/apache/tinkerpop/master/docs/static/ima
* Changed `Tree` to no longer extend `HashMap`; it is now a final class with a tree-shaped API (`childAt`, `hasChild`, `contains`, `findSubtree`, `getOrCreateChild`, `getNodesAtDepth`, `getLeafNodes`, `nodeCount`) and is no longer a `Map`.
* Changed `count(local)` on a `Tree` to return the total node count (`Tree.nodeCount()`) instead of the root-entry count.
* Changed Tree class in Java to not extend from HashMap and offered a new tree-shaped API for navigation.
+* Added multi-label support for vertices with configurable `LabelCardinality` (`ONE`, `ONE_OR_MORE`, `ZERO_OR_MORE`).
+* Added `labels()` step to emit each vertex label as a separate traverser.
+* Added `addLabel()` and `dropLabel()`/`dropLabels()` steps for vertex label mutation.
+* Added `LabelCardinalityValidator` utility for constraint enforcement separated from the `LabelCardinality` enum.
+* Added `with("multilabel")` source configuration for `elementMap()` and `valueMap()` to return labels as a set.
+* Added `LabelsDropVerificationStrategy` to prevent accidental `labels().drop()` usage.
+* Added multi-label syntax to `addV()` and `mergeV()` with append-only `onMatch` semantics.
* Added typed numeric wrappers and `preciseNumbers` connection option to `gremlin-javascript` for explicit control over numeric type serialization and deserialization.
* Added `NextN(n)` to `Traversal` in `gremlin-go` for batched result iteration, providing API parity with `next(n)` in the Java, Python, and .NET GLVs, and updated the Go translators in `gremlin-core` and `gremlin-javascript` to emit `NextN(n)` for the batched form.
* Added Provider Defined Types (PDT) support — graph providers can define custom types via `@ProviderDefined` annotation that serialize/deserialize seamlessly across all GLVs without driver-side configuration. Replaces TP3 custom type mechanism.
diff --git a/docker/gremlin-server/gremlin-server-integration.yaml b/docker/gremlin-server/gremlin-server-integration.yaml
index 1880b34810..a730970f85 100644
--- a/docker/gremlin-server/gremlin-server-integration.yaml
+++ b/docker/gremlin-server/gremlin-server-integration.yaml
@@ -23,6 +23,9 @@ graphs: {
graph: {
configuration: conf/tinkergraph-service.properties,
traversalSources: [{name: g}, {name: ggraph}]},
+ multilabel: {
+ configuration: conf/tinkergraph-multilabel.properties,
+ traversalSources: [{name: gmultilabel}]},
immutable: {
configuration: conf/tinkergraph-service.properties,
traversalSources: [{name: gimmutable}]},
diff --git a/docs/src/dev/provider/gremlin-semantics.asciidoc b/docs/src/dev/provider/gremlin-semantics.asciidoc
index 1ec854de20..5713ab1b6d 100644
--- a/docs/src/dev/provider/gremlin-semantics.asciidoc
+++ b/docs/src/dev/provider/gremlin-semantics.asciidoc
@@ -587,6 +587,69 @@ See: link:https://github.com/apache/tinkerpop/tree/x.y.z/gremlin-core/src/main/j
link:https://github.com/apache/tinkerpop/tree/x.y.z/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/AddVertexStartStep.java[source (start)],
link:https://tinkerpop.apache.org/docs/x.y.z/reference/#addvertex-step[reference]
+=== addLabel()
+
+*Description:* Adds one or more labels to an element.
+
+*Syntax:* `addLabel(String label, String... moreLabels)` | `addLabel(Traversal<?, String> labelTraversal)`
+
+[width="100%",options="header"]
+|=========================================================
+|Start Step |Mid Step |Modulated |Domain |Range
+|N |Y |N |`Element` |`Element`
+|=========================================================
+
+*Arguments:*
+
+* `label` - The label to add.
+* `moreLabels` - Additional labels to add.
+* `labelTraversal` - A traversal that produces labels to add.
+
+*Considerations:*
+
+The graph must be configured with a `LabelCardinality` that supports mutation (`ONE_OR_MORE` or `ZERO_OR_MORE`).
+Adding a label that already exists on the element is a no-op. The step returns the element (sideEffect semantics).
+
+*Exceptions*
+
+* If the graph's `LabelCardinality` does not support mutation, an `IllegalStateException` will be thrown.
+* If any label argument is null or empty, an `IllegalArgumentException` will be thrown.
+
+See: link:https://github.com/apache/tinkerpop/tree/x.y.z/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/sideEffect/AddLabelStep.java[source],
+link:https://tinkerpop.apache.org/docs/x.y.z/reference/#addlabel-step[reference]
+
+=== dropLabel()
+
+*Description:* Removes one or more specific labels from an element, or removes all labels.
+
+*Syntax:* `dropLabel(String label, String... moreLabels)` | `dropLabel(Traversal<?, String> labelTraversal)` | `dropLabels()`
+
+[width="100%",options="header"]
+|=========================================================
+|Start Step |Mid Step |Modulated |Domain |Range
+|N |Y |N |`Element` |`Element`
+|=========================================================
+
+*Arguments:*
+
+* `label` - The label to remove.
+* `moreLabels` - Additional labels to remove.
+* `labelTraversal` - A traversal that produces labels to remove.
+
+*Considerations:*
+
+The graph must be configured with a `LabelCardinality` that supports mutation. Dropping a label that does not exist
+on the element is a no-op. `dropLabels()` removes all labels (only valid with `ZERO_OR_MORE`). The step returns the
+element (sideEffect semantics).
+
+*Exceptions*
+
+* If the graph's `LabelCardinality` does not support mutation, an `IllegalStateException` will be thrown.
+* If `dropLabel()` or `dropLabels()` would violate the minimum label count, an `IllegalStateException` will be thrown.
+
+See: link:https://github.com/apache/tinkerpop/tree/x.y.z/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/sideEffect/DropLabelsStep.java[source],
+link:https://tinkerpop.apache.org/docs/x.y.z/reference/#droplabel-step[reference]
+
[[all-step]]
=== all()
@@ -1667,6 +1730,29 @@ See: link:https://github.com/apache/tinkerpop/tree/x.y.z/gremlin-core/src/main/j
link:https://github.com/apache/tinkerpop/tree/x.y.z/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/LengthLocalStep.java[source (local)],
link:https://tinkerpop.apache.org/docs/x.y.z/reference/#length-step[reference]
+=== labels()
+
+*Description:* Maps an element to its labels, emitting one traverser per label.
+
+*Syntax:* `labels()`
+
+[width="100%",options="header"]
+|=========================================================
+|Start Step |Mid Step |Modulated |Domain |Range
+|N |Y |N |`Element` |`String`
+|=========================================================
+
+*Considerations:*
+
+For vertices with a single label, `labels()` emits one traverser (equivalent to `label()`). For multi-label vertices,
+it emits one traverser per label. For vertices with zero labels (`ZERO_OR_MORE` mode), no traversers are emitted.
+
+`hasLabel("a", "b")` uses OR semantics: it matches any vertex that has label "a" or label "b". To match vertices
+with all specified labels, chain calls: `hasLabel("a").hasLabel("b")`.
+
+See: link:https://github.com/apache/tinkerpop/tree/x.y.z/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/LabelsStep.java[source],
+link:https://tinkerpop.apache.org/docs/x.y.z/reference/#labels-step[reference]
+
[[local-step]]
=== local()
diff --git a/docs/src/reference/implementations-tinkergraph.asciidoc b/docs/src/reference/implementations-tinkergraph.asciidoc
index f9ce642b74..9c23861893 100644
--- a/docs/src/reference/implementations-tinkergraph.asciidoc
+++ b/docs/src/reference/implementations-tinkergraph.asciidoc
@@ -166,6 +166,7 @@ TinkerGraph has several settings that can be provided on creation via `Configura
|gremlin.tinkergraph.vertexPropertyIdManager |The `IdManager` implementation to use for vertex properties.
|gremlin.tinkergraph.defaultVertexPropertyCardinality |The default `VertexProperty.Cardinality` to use when `Vertex.property(k,v)` is called.
|gremlin.tinkergraph.allowNullPropertyValues |A boolean value that determines whether or not `null` property values are allowed and defaults to `false`.
+|gremlin.tinkergraph.vertexLabelCardinality |The `LabelCardinality` for vertices. Options are `ONE` (default, single immutable label, backward-compatible with 3.x), `ONE_OR_MORE` (at least one label, mutable), or `ZERO_OR_MORE` (fully flexible, zero or more labels). See <<tinkergraph-multi-label>>.
|gremlin.tinkergraph.graphLocation |The path and file name for where TinkerGraph should persist the graph data. If a
value is specified here, the `gremlin.tinkergraph.graphFormat` should also be specified. If this value is not
included (default), then the graph will stay in-memory and not be loaded/persisted to disk.
@@ -219,6 +220,31 @@ g.io("data/tinkerpop-crew.kryo").read().iterate()
g.V().properties()
----
+[[tinkergraph-multi-label]]
+=== Multi-Label Support
+
+TinkerGraph supports multiple labels per vertex when `gremlin.tinkergraph.vertexLabelCardinality` is set to
+`ONE_OR_MORE` or `ZERO_OR_MORE`. This enables use of the `addLabel()`, `dropLabel()`, `dropLabels()`, and `labels()`
+traversal steps.
+
+[source,groovy]
+----
+conf = new BaseConfiguration()
+conf.setProperty("gremlin.tinkergraph.vertexLabelCardinality", "ZERO_OR_MORE")
+graph = TinkerGraph.open(conf)
+g = traversal().with(graph)
+g.addV("person","employee").property("name","marko").iterate()
+g.V().has("name","marko").labels() // emits: person, employee
+g.V().has("name","marko").addLabel("manager").labels() // emits: person, employee, manager
+g.V().has("name","marko").dropLabel("employee").labels() // emits: person, manager
+----
+
+The `hasLabel()` step works with multi-label vertices using OR semantics: `hasLabel("a","b")` matches any vertex that
+has label "a" OR label "b". To match vertices having both labels, chain multiple `hasLabel()` calls:
+`hasLabel("a").hasLabel("b")`.
+
+IMPORTANT: Edge labels are currently fixed at cardinality `ONE` and are not configurable.
+
[[tinkergraph-gremlin-tx]]
=== Transactions
diff --git a/docs/src/reference/the-traversal.asciidoc b/docs/src/reference/the-traversal.asciidoc
index b8886a651a..90521ac02e 100644
--- a/docs/src/reference/the-traversal.asciidoc
+++ b/docs/src/reference/the-traversal.asciidoc
@@ -594,6 +594,33 @@ link:++https://tinkerpop.apache.org/javadocs/x.y.z/core/org/apache/tinkerpop/gre
link:++https://tinkerpop.apache.org/javadocs/x.y.z/core/org/apache/tinkerpop/gremlin/process/traversal/dsl/graph/GraphTraversal.html#addV(java.lang.String)++[`addV(String)`],
link:++https://tinkerpop.apache.org/javadocs/x.y.z/core/org/apache/tinkerpop/gremlin/process/traversal/dsl/graph/GraphTraversal.html#addV(org.apache.tinkerpop.gremlin.process.traversal.Traversal)++[`addV(Traversal)`]
+[[addlabel-step]]
+=== AddLabel Step
+
+The `addLabel()`-step (*sideEffect*) adds one or more labels to an element. The graph must be configured with a
+`LabelCardinality` that supports mutation (e.g. `ZERO_OR_MORE` or `ONE_OR_MORE`). Adding a label that already exists
+on the element is a no-op.
+
+[gremlin-groovy]
+----
+conf = new BaseConfiguration()
+conf.setProperty("gremlin.tinkergraph.vertexLabelCardinality", "ZERO_OR_MORE")
+graph = TinkerGraph.open(conf)
+g = traversal().with(graph)
+g.addV('person').property('name','marko').addLabel('employee').labels()
+g.V().has('name','marko').hasLabel('person')
+g.V().has('name','marko').hasLabel('employee')
+----
+
+NOTE: When `LabelCardinality` is set to `ONE` (the default), calling `addLabel()` will throw an
+`IllegalStateException` since labels are immutable in that mode.
+
+See: <<labels-step,labels() step>>, <<droplabel-step,dropLabel() step>>
+
+*Additional References*
+
+link:++https://tinkerpop.apache.org/javadocs/x.y.z/core/org/apache/tinkerpop/gremlin/process/traversal/dsl/graph/GraphTraversal.html#addLabel(java.lang.String,java.lang.String...)++[`addLabel(String, String...)`]
+
[[aggregate-step]]
=== [[store-step]]Aggregate Step
@@ -1717,6 +1744,39 @@ g.V()
* link:++https://tinkerpop.apache.org/javadocs/x.y.z/core/org/apache/tinkerpop/gremlin/process/traversal/dsl/graph/GraphTraversal.html#drop()++[`drop()`]
+[[droplabel-step]]
+=== DropLabel Step
+
+The `dropLabel()`-step (*sideEffect*) removes one or more specific labels from an element. The `dropLabels()`-step
+removes all labels. The graph must be configured with a `LabelCardinality` that supports mutation. Dropping a label
+that does not exist on the element is a no-op.
+
+[gremlin-groovy]
+----
+conf = new BaseConfiguration()
+conf.setProperty("gremlin.tinkergraph.vertexLabelCardinality", "ZERO_OR_MORE")
+graph = TinkerGraph.open(conf)
+g = traversal().with(graph)
+v = g.addV('person').property('name','marko').addLabel('employee').addLabel('manager').next()
+g.V(v).labels()
+g.V(v).dropLabel('manager').labels()
+g.V(v).dropLabels().labels()
+----
+
+NOTE: With `LabelCardinality.ONE_OR_MORE`, `dropLabels()` always throws and `dropLabel()` throws if it would
+leave the element with zero labels.
+
+IMPORTANT: Do not confuse `dropLabel()` with `labels().drop()`. The latter attempts to drop the string traversers
+emitted by `labels()` and is blocked by the `LabelsDropVerificationStrategy`. Use `dropLabel()` or `dropLabels()` to
+remove labels from vertices.
+
+See: <<addlabel-step,addLabel() step>>, <<labels-step,labels() step>>
+
+*Additional References*
+
+link:++https://tinkerpop.apache.org/javadocs/x.y.z/core/org/apache/tinkerpop/gremlin/process/traversal/dsl/graph/GraphTraversal.html#dropLabel(java.lang.String,java.lang.String...)++[`dropLabel(String, String...)`],
+link:++https://tinkerpop.apache.org/javadocs/x.y.z/core/org/apache/tinkerpop/gremlin/process/traversal/dsl/graph/GraphTraversal.html#dropLabels()++[`dropLabels()`]
+
[[e-step]]
=== E Step
@@ -1784,6 +1844,28 @@ g.V().has('name','marko').properties('location').elementMap()
IMPORTANT: The `elementMap()`-step does not return the vertex labels for incident vertices when using `GraphComputer`
as the `id` is the only available data to the star graph.
+For multi-label graphs, `elementMap()` returns labels as a single string by default. To receive all labels as a
+set, use `with("multilabel")` either per-traversal or on a persistent source:
+
+[gremlin-groovy]
+----
+conf = new BaseConfiguration()
+conf.setProperty("gremlin.tinkergraph.vertexLabelCardinality", "ZERO_OR_MORE")
+graph = TinkerGraph.open(conf)
+g = traversal().with(graph)
+g.addV('person').property('name','marko').addLabel('employee').addLabel('manager').iterate()
+g.V().has('name','marko').elementMap() <1>
+g.with("multilabel").V().has('name','marko').elementMap() <2>
+gml = g.with("multilabel")
+gml.V().has('name','marko').elementMap() <3>
+gml.V().has('name','marko').valueMap(true) <4>
+----
+
+<1> Without `"multilabel"`, the label entry is a single string.
+<2> Per-traversal `with("multilabel")` returns all labels as a set.
+<3> A persistent source avoids repeating `with("multilabel")` on each traversal.
+<4> `valueMap(true)` also respects the `"multilabel"` configuration.
+
*Additional References*
link:++https://tinkerpop.apache.org/javadocs/x.y.z/core/org/apache/tinkerpop/gremlin/process/traversal/dsl/graph/GraphTraversal.html#elementMap(java.lang.String...)++[`elementMap(String...)`]
@@ -2504,10 +2586,37 @@ g.V(1).outE().label()
g.V(1).properties().label()
----
+NOTE: For graphs that support multiple labels per vertex, `label()` returns only one label and the choice is
+non-deterministic (implementation-dependent ordering). Use the <<labels-step,labels() step>> to retrieve all labels
+reliably.
+
*Additional References*
link:++https://tinkerpop.apache.org/javadocs/x.y.z/core/org/apache/tinkerpop/gremlin/process/traversal/dsl/graph/GraphTraversal.html#label()++[`label()`]
+[[labels-step]]
+=== Labels Step
+
+The `labels()`-step (*flatMap*) takes an `Element` and emits each of its labels as a separate traverser. For elements
+with a single label this behaves identically to `label()`. For multi-label elements, it emits one traverser per label.
+
+[gremlin-groovy]
+----
+conf = new BaseConfiguration()
+conf.setProperty("gremlin.tinkergraph.vertexLabelCardinality", "ZERO_OR_MORE")
+graph = TinkerGraph.open(conf)
+g = traversal().with(graph)
+g.addV('person').property('name','marko').addLabel('employee').iterate()
+g.V().labels()
+g.V().labels().count()
+----
+
+See: <<label-step,label() step>>, <<addlabel-step,addLabel() step>>, <<droplabel-step,dropLabel() step>>
+
+*Additional References*
+
+link:++https://tinkerpop.apache.org/javadocs/x.y.z/core/org/apache/tinkerpop/gremlin/process/traversal/dsl/graph/GraphTraversal.html#labels()++[`labels()`]
+
[[length-step]]
=== Length Step
@@ -5386,6 +5495,23 @@ g.V().hasLabel('person').valueMap('name').with(WithOptions.tokens, WithOptions.l
g.V().hasLabel('person').properties('location').valueMap().with(WithOptions.tokens, WithOptions.values)
----
+For multi-label graphs, the label value in the map is a single string by default. Use `with("multilabel")` to
+receive all labels as a set:
+
+[gremlin-groovy]
+----
+conf = new BaseConfiguration()
+conf.setProperty("gremlin.tinkergraph.vertexLabelCardinality", "ZERO_OR_MORE")
+graph = TinkerGraph.open(conf)
+g = traversal().with(graph)
+g.addV('person').property('name','marko').addLabel('employee').iterate()
+g.V().has('name','marko').valueMap(true) <1>
+g.with("multilabel").V().has('name','marko').valueMap(true) <2>
+----
+
+<1> Without `"multilabel"`, the label entry is a single string.
+<2> With `"multilabel"`, all labels are returned as a set.
+
*Additional References*
link:++https://tinkerpop.apache.org/javadocs/x.y.z/core/org/apache/tinkerpop/gremlin/process/traversal/dsl/graph/GraphTraversal.html#valueMap(java.lang.String...)++[`valueMap(String...)`]
diff --git a/docs/src/upgrade/release-4.x.x.asciidoc b/docs/src/upgrade/release-4.x.x.asciidoc
index 163404417f..b56d335119 100644
--- a/docs/src/upgrade/release-4.x.x.asciidoc
+++ b/docs/src/upgrade/release-4.x.x.asciidoc
@@ -1,1686 +1,1783 @@
-////
-Licensed to the Apache Software Foundation (ASF) under one
-or more contributor license agreements. See the NOTICE file
-distributed with this work for additional information
-regarding copyright ownership. The ASF licenses this file
-to you under the Apache License, Version 2.0 (the
-"License"); you may not use this file except in compliance
-with the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing,
-software distributed under the License is distributed on an
-"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-KIND, either express or implied. See the License for the
-specific language governing permissions and limitations
-under the License.
-////
-
-= TinkerPop 4.0.0
-
-image::gremlins-wildest-dreams.png[width=185]
-
-*Gremlin's Wildest Dreams*
-
-== TinkerPop 4.0.0
-
-*Release Date: NOT OFFICIALLY RELEASED YET*
-
-Please see the link:https://github.com/apache/tinkerpop/blob/4.0.0/CHANGELOG.asciidoc#release-4-0-0[changelog] for a
-complete list of all the modifications that are part of this release.
-
-=== Upgrading for Users
-
-===== Declarative Pattern Matching
-
-Gremlin has always offered both imperative and declarative styles to writing graph queries. While the imperative style
-has largely dominated examples and usages, the `match` step has always provided a declarative way to express queries.
-The syntax for `match` looked something like this:
-
-[source,text]
-----
-gremlin> g.V().match(__.as("a").hasLabel("person").out("created").hasLabel("software").as("s"),
-......1> __.as("s").hasLabel("software").in("created").hasLabel("person").as("b")).
-......2> where("a", neq("b")).
-......3> select("a", "b", "s").by("name")
-==>[a:marko,b:josh,s:lop]
-==>[a:marko,b:peter,s:lop]
-==>[a:josh,b:marko,s:lop]
-==>[a:josh,b:peter,s:lop]
-==>[a:peter,b:marko,s:lop]
-==>[a:peter,b:josh,s:lop]
-----
-
-While this approach worked, it was syntactically complex and since `match` took an arbitrary `Traversal` as arguments,
-the declarative style wasn't necessarily enforced well. Moreover, providers found it complicated to optimize `match` as
-a step, which meant that, more often than not, it was more performant to simply write the imperative form of the query,
-which could take advantage of normal optimization patterns. As a result, `match` never really gained a main stream sort
-of usage beyond some fairly narrow use cases.
-
-In TinkerPop 4.0.0, `match` has a new direction. Instead of taking Gremlin traversals to define the match pattern, it
-takes a query string that could technically be any declarative graph query language. Using
-link:https://www.iso.org/standard/76120.html[GQL] as an example, the previous Gremlin query using the old `match` style
-would look like this:
-
-[source,text]
-----
-gremlin> g.match("MATCH (a:person)-[:created]->(s:software), (b:person)-[:created]->(s)").
-......1> where("a", neq("b")).
-......2> select("a", "b", "s").by("name")
-==>[a:marko,b:josh,s:lop]
-==>[a:marko,b:peter,s:lop]
-==>[a:josh,b:marko,s:lop]
-==>[a:josh,b:peter,s:lop]
-==>[a:peter,b:marko,s:lop]
-==>[a:peter,b:josh,s:lop]
-----
-
-With `match` redesigned in this way users have the opportunity to take advantage of the strengths of declarative query
-languages, where it makes sense, while equally retaining the power and feel that Gremlin has always had. The promise of
-Gremlin being both imperative and declarative offers a much more compelling story with this model.
-
-NOTE: The traversal-based form of `match` (e.g. `g.V().match(as("a").out().as("b"))`) is deprecated as of
-TinkerPop 4.0.0 and will be removed in a future release. Users should migrate to the new `match(String)` API.
-
-TinkerPop ships a reference GQL engine for `match()` via the optional `gql-gremlin` module. The engine implements the
-link:https://tinkerpop.apache.org/docs/x.y.z/reference/#tinkergql[TinkerGQL] dialect — a deliberate minimal subset of
-ISO GQL `MATCH` syntax — and works against any `Graph` implementation through a thin set of default interface methods.
-TinkerGraph uses it out of the box with no configuration required. Graph providers that want to offer TinkerGQL support
-can add the `gql-gremlin` dependency and register `GqlDeclarativeMatchStrategy` as described in the
-link:https://tinkerpop.apache.org/docs/x.y.z/dev/provider/#tinkerpop-providers-tinkergql[provider documentation].
-
-==== Request Interceptors
-
-When TinkerPop supported WebSockets prior to 4.0.0, the Java driver offered a `RequestInterceptor` interface (and
-its predecessor, `HandshakeInterceptor`) that allowed modification of the raw Netty `FullHttpRequest`. For WebSocket
-connections, the interceptor only ran on the initial HTTP upgrade handshake. With the move to HTTP, the notion of
-the "interceptor" has shifted to a per-request concern that is now standardized across all GLVs.
-
-All GLVs now support request interceptors, which allow modification of the HTTP request before it is sent to the
-server. An interceptor is a function that receives the mutable HTTP request object and can modify headers, the
-request body, the URI, or the HTTP method. Interceptors are run in the order they are registered.
-
-The most common use case for interceptors is authentication (e.g., SigV4 signing), but they can also be used to add
-provider-specific fields, inject custom headers, or transform the request body.
-
-Here is a simple Java example that adds a custom header:
-
-[source,java]
-----
-Cluster cluster = Cluster.build("localhost")
- .interceptors(request -> request.headers().put("X-Custom-Header", "value"))
- .create();
-----
-
-Authentication is also an interceptor. Each GLV provides convenience methods (e.g., `Auth.basic()`, `Auth.sigv4()`)
-that return interceptors and can be registered alongside custom ones.
-
-For full details on the interceptor API for each language variant, refer to the RequestInterceptor section in
-each GLV's documentation in the
-link:https://tinkerpop.apache.org/docs/x.y.z/reference/#gremlin-drivers-variants[Gremlin Drivers and Variants]
-reference.
-
-==== Gremlator
-
-link:https://gremlator.com[Gremlator] has been rebuilt entirely in JavaScript as a browser-based single-page
-application and is now an official part of the Apache TinkerPop project. It translates Gremlin queries into
-equivalent representations in all supported language variants: Groovy, Java, Python, JavaScript, Go, .NET, and an
-anonymized form. The original gremlator.com was a prototype built by TinkerPop committer Dave Bechberger; the
-previous implementation required Java and a running Gremlin Server, whereas the new version runs entirely in the
-browser with no server infrastructure needed.
-
-==== GLV Transaction Support
-
-All non-Java Gremlin Language Variants (gremlin-python, gremlin-go, gremlin-javascript, gremlin-dotnet) now support
-explicit remote transactions over HTTP. The transaction model is the same across all GLVs: begin a transaction, submit
-traversals within it, then commit or rollback. Data is isolated until committed.
-
-Each GLV provides two entry points:
-
-* **Traversal API**: `g.tx().begin()` returns a transaction-bound `GraphTraversalSource`
-* **Driver API**: `client.transact()` (or `client.Transact()` in .NET) returns a `Transaction` with `submit()` methods
-
-Key behaviors consistent across all GLVs:
-
-* Transactions are not thread-safe. All operations must be sequential.
-* The default close behavior is rollback (partial work discarded if commit is not called explicitly).
-* Transactions are single-use. After commit or rollback, a new transaction must be created.
-* `gtx.tx()` returns the same transaction object (enabling `gtx.tx().commit()` pattern from the Traversal API).
-
-See the <<gremlin-drivers-variants,Gremlin Drivers and Variants>> reference documentation for language-specific
-syntax and examples.
-
-==== Transaction Default Close Behavior Changed
-
-The default behavior of `close()` on a remote transaction has been changed from `commit` to `rollback` across all
-GLVs (including the Java driver). This aligns with the embedded graph transaction default and is the safer behavior:
-partial work is discarded if the user forgets to call `commit()`. In Java (both remote and embedded mode), the behavior
-can still be overridden via `tx.onClose(Transaction.CLOSE_BEHAVIOR.COMMIT)`. The non-Java GLVs do not support
-configuring close behavior and always rollback.
-
-==== Removed `uuid` Dependency in gremlin-javascript
-
-The `uuid` npm package has been removed from `gremlin-javascript`. UUID generation now uses the built-in
-`globalThis.crypto.randomUUID()` API, which is available in Node.js 19+ and all modern browsers.
-
-This change has no impact on how UUID values are sent to or received from the server — UUID serialization and
-deserialization in GraphBinary is unchanged. Applications that depend on the `uuid` package solely because
-`gremlin-javascript` brought it in as a transitive dependency should add it directly to their own `package.json`
-if they still need it.
-
-==== JS HTTP Streaming Response Support
-
-The JavaScript driver now supports incremental HTTP streaming. Results are deserialized from the server response as
-they arrive, rather than buffering the entire response before processing.
-
-Traversal API terminal steps (`next()`, `toList()`, `hasNext()`) are now truly incremental. `next()`
-returns the first result as soon as it is deserialized from the wire, without waiting for the full response.
-In 3.x, `next()` waited for all WebSocket frames before returning.
-
-`Client.stream()` now returns an `AsyncGenerator` for direct incremental consumption. This is a breaking change
-from 3.x where `stream()` returned a Node.js `Readable`. The new return type works in both Node.js and browsers:
-
-[source,javascript]
-----
-// 3.x — Readable stream (no longer supported)
-// const stream = client.stream('g.V()');
-// stream.on('data', (resultSet) => { ... });
-
-// 4.0 — AsyncGenerator
-for await (const item of client.stream('g.V()', null)) {
- console.log(item);
- if (someCondition) break; // stops reading from the HTTP stream
-}
-----
-
-`Client.submit()` remains unchanged. It still buffers the full response and returns `Promise<ResultSet>`.
-
-==== New Gremlin-Lang Literals
-
-The canonical Gremlin grammar now includes literal syntax for `Character`, `Duration`, and `Binary` types. These
-literals can be used directly in traversals without falling back to parameter serialization.
-
-===== Character
-
-A character literal is a single-character string with a `c` suffix:
-
-[source,text]
-----
-g.V().has("initial","M"c)
-----
-
-NOTE: Character is not supported in gremlin-go or gremlin-javascript.
-
-===== Duration
-
-A duration literal uses seconds and nanoseconds with an optional sign flag:
-
-[source,text]
-----
-Duration(seconds,nanos)
-Duration(seconds,nanos,false)
-----
-
-The first argument is seconds (non-negative integer), the second is nanoseconds (integer, 0 to 999999999). The
-optional third argument is an `isPositive` boolean that defaults to `true` when omitted. Set it to `false` for
-negative durations.
-
-[source,text]
-----
-g.V().has("length",P.gt(Duration(3600,0)))
-----
-
-NOTE: Python's `timedelta` has microsecond resolution, so sub-microsecond nanosecond values are truncated.
-.NET's `TimeSpan` has 100-nanosecond tick resolution, so sub-100ns values are truncated.
-
-NOTE: Duration is not supported in gremlin-javascript.
-
-===== Binary
-
-A binary literal wraps a base64-encoded string:
-
-[source,text]
-----
-Binary("AQID")
-Binary("")
-----
-
-Each GLV maps this to its native byte array type:
-
-[source,text]
-----
-g.V().has("blob",P.eq(Binary("AQID")))
-----
-
-See: link:https://issues.apache.org/jira/browse/TINKERPOP-3153[TINKERPOP-3153]
-
-==== Python HTTP Streaming Response Support
-
-The Python driver now streams results directly from the HTTP response body through the configured
-`response_serializer`. Results are available to the caller as they arrive from the server, rather than waiting for
-the full response to be buffered in memory. This improves memory efficiency for large result sets and reduces
-time-to-first-result.
-
-Traversal API terminal steps (`next()`, `to_list()`, `has_next()`) are now truly incremental. `next()` returns the
-first result as soon as it is deserialized from the wire, without waiting for the full response. In 3.x, `next()`
-waited for all data to be buffered before returning.
-
-The following internal APIs have changed:
-
-- `max_content_length` is no longer supported. Response size limits should be configured server-side via
- `maxRequestContentLength`.
-- The built-in response serializer is `GraphBinarySerializersV4`. The receive path dispatches through the
- configured `response_serializer`.
-- `ResultSet` now yields individual items instead of lists when iterated. Code that uses `results += result`
- to accumulate results from a `ResultSet` iterator must change to `results.append(result)`. The `to_list()`
- and `all()` APIs are unaffected and remain the recommended way to collect results.
-
-==== Python Driver Simplification — Removed GraphSON, Abstract Base Classes, and Protocol Layer
-
-The `AbstractBaseTransport`, `AbstractBaseProtocol`, and `GremlinServerHTTPProtocol` classes have been removed from
-`gremlin-python`. The protocol layer's request-building logic (serialization, headers, interceptors, auth) has been
-merged directly into `Connection`. The driver now uses `AiohttpHTTPTransport` directly without an abstract transport
-interface.
-
-`GremlinServerError` has moved from `gremlin_python.driver.protocol` to `gremlin_python.driver.connection`:
-
-The `GraphSONSerializersV4` class and the `gremlin_python.structure.io.graphsonV4` module have been removed.
-GraphBinary is the only supported wire format for the Python driver in TinkerPop 4. Code that constructed
-`GraphSONSerializersV4()` or imported from `gremlin_python.structure.io.graphsonV4` must switch to
-`GraphBinarySerializersV4` (the default `request_serializer` and `response_serializer`):
-
-[source,python]
-----
-# Before
-from gremlin_python.driver.protocol import GremlinServerError
-
-# After
-from gremlin_python.driver.connection import GremlinServerError
-----
-
-The `protocol_factory` and `transport_factory` parameters have been removed from `Client`,
-`DriverRemoteConnection`, and `Connection`. Users who were passing a custom `protocol_factory` should use the
-`request_serializer`, `response_serializer`, `auth`, and `interceptors` parameters directly instead — these cover
-all functionality that `GremlinServerHTTPProtocol` previously provided.
-
-Transport options like SSL and timeouts are now passed as keyword arguments directly:
-
-[source,python]
-----
-# Before
-from gremlin_python.driver.aiohttp.transport import AiohttpHTTPTransport
-Client(url, 'g', transport_factory=lambda: AiohttpHTTPTransport(ssl_options=ctx, read_timeout=30))
-
-# After
-Client(url, 'g', ssl_options=ctx, read_timeout=30)
-----
-
-The `Connection` constructor signature has changed. The `protocol` and `transport_factory` positional arguments have
-been removed. Transport kwargs are forwarded to `AiohttpHTTPTransport` internally:
-
-[source,python]
-----
-# Before
-Connection(url, traversal_source, protocol, transport_factory, executor, pool)
-
-# After
-Connection(url, traversal_source, executor, pool,
- request_serializer=None, response_serializer=None,
- auth=None, interceptors=None, **transport_kwargs)
-----
-
-Custom transport implementations are no longer supported. The driver uses `AiohttpHTTPTransport` directly.
-
-==== Removal of sparql-gremlin
-
-The `sparql-gremlin` module has been removed following a prolonged period of inactivity. There is currently no direct
-replacement planned for this functionality.
-
-See: link:https://issues.apache.org/jira/browse/TINKERPOP-3249[TINKERPOP-3249]
-
-==== Runtime Upgrades
-
-The minimum target framework is now `net8.0` (previously `netstandard2.0;net6.0`). .NET 6 reached end-of-life in
-November 2024; .NET 8 is the current LTS release.
-
-==== .NET HTTP Streaming Response Support
-
-The .NET driver (`Gremlin.Net`) now uses streaming deserialization, results are deserialized incrementally from the
-HTTP response stream as bytes arrive over the network, rather than buffering the entire response before processing.
-This reduces memory usage and latency for large result sets.
-
-The traversal API (`Next()`, `ToList()`, `HasNext()`, `ToSet()`, `Iterate()`) is unchanged — these methods block
-internally on the async stream, so existing traversal code works without modification.
-
-`ResultSet<T>` no longer implements `IReadOnlyCollection<T>`. It now implements `IAsyncEnumerable<T>`, backed by a
-`Channel<T>` that receives items from a background deserialization task. Users who access `ResultSet<T>` directly
-via `GremlinClient.SubmitAsync<T>()` will need to update their code:
-
-[source,csharp]
-----
-// 3.x — ResultSet was IReadOnlyCollection<T>
-var resultSet = await client.SubmitAsync<int>("g.inject(1,2,3)");
-var count = resultSet.Count; // no longer available
-foreach (var item in resultSet) { } // no longer available
-
-// 4.0 — ResultSet is IAsyncEnumerable<T>
-var resultSet = await client.SubmitAsync<int>("g.inject(1,2,3)");
-var list = await resultSet.ToListAsync(); // materialize if you need Count
-await foreach (var item in resultSet) { } // async iteration
-----
-
-The `IMessageSerializer` interface has also changed: `DeserializeMessageAsync` now accepts a `Stream` and returns
-`IAsyncEnumerable<object>` instead of accepting `byte[]` and returning `Task<ResponseMessage<List<object>>>`.
-Custom serializer implementations will need to be updated. The `ResponseMessage<T>` type has been removed.
-
-With streaming, server errors (`ResponseException`) are now thrown during result iteration rather than during
-`SubmitAsync`. Code that catches `ResponseException` around `SubmitAsync` should be updated to catch around the
-result consumption instead:
-
-[source,csharp]
-----
-// 3.x — exception thrown during SubmitAsync
-try {
- var resultSet = await client.SubmitAsync<int>("invalid");
-} catch (ResponseException ex) { ... }
-
-// 4.0 — exception thrown during iteration
-var resultSet = await client.SubmitAsync<int>("invalid");
-try {
- var list = await resultSet.ToListAsync();
-} catch (ResponseException ex) { ... }
-----
-
-The traversal API is not affected — `Next()`, `ToList()`, etc. still throw `ResponseException` directly since they
-block on the async stream internally.
-
-==== Streaming Response Deserialization in gremlin-driver
-
-The Java driver now deserializes HTTP responses incrementally, delivering results to the `ResultSet` as they arrive
-rather than buffering the entire response. This reduces time-to-first-result for large result sets.
-
-This change is automatic and requires no code changes. It applies only when using the default GraphBinary serializer.
-Custom `MessageSerializer` implementations fall back to the non-streaming pipeline that buffers the full response
-before deserialization. The `ResultSet` API is unchanged.
-
-==== More Secure Gremlin Server
-
-Previous versions of Gremlin Server relied on a Gremlin-flavored Groovy `ScriptEngine` for basic server initialization,
-which covered binding traversal sources, loading data, and running lifecycle hooks all set up by Groovy initialization
-scripts. This meant the Groovy `ScriptEngine` was active by default, even for users who only needed to send standard
-Gremlin queries.
-
-TinkerPop 4.0 addresses this in two ways. First, `gremlin-lang` replaces `gremlin-groovy` as the default `ScriptEngine`
-for remote script execution, so standard Gremlin queries no longer require a general-purpose scripting engine. Second,
-server initialization is now handled through declarative YAML configuration, removing the last reason Groovy needed to
-be active by default.
-
-As of this release, Groovy is completely disabled by default throughout the entire server lifecycle. Users who
-explicitly need Groovy script execution can still opt in, but it is no longer required for any standard usage. A future
-release may remove Groovy as an installed option in the server distribution altogether.
-
-===== Simplified Server Configuration
-
-The most basic server setup, initializing a basic graph with a traversal source, previously required a Groovy init
-script just to create the `g` binding. Now, any graph defined in the `graphs` section automatically gets a
-`TraversalSource` according to these rules:
-
-* A graph named `graph` is implicitly bound to `g`
-* All others are bound to `g_<graph-name>` (e.g. `modern` gets `g_modern`)
-
-A fully functional minimal configuration is now simply:
-
-[source,yaml]
-----
-graphs: {
- graph: conf/tinkergraph-empty.properties}
-----
-
-===== Strategy Configuration via `traversalSources`
-
-For cases that require custom traversalSource naming or strategies on a `TraversalSource` (e.g. `ReadOnlyStrategy`), the
-`traversalSources` list within a graph entry provides explicit control without scripting:
-
-[source,yaml]
-----
-graphs: {
- graph: {
- configuration: conf/tinkergraph-empty.properties,
- traversalSources: [
- {name: g},
- {name: gReadOnly, gremlinExpression: "g.withStrategies(ReadOnlyStrategy)"}]}}
-----
-
-Each entry specifies:
-
-- `name` (required): the binding name for the `TraversalSource`
-- `gremlinExpression` (optional): a Gremlin expression evaluated with a base traversal source bound as `g`
-- `language` (optional): which `ScriptEngine` to use for the expression (defaults to `gremlin-lang`, or the sole
-configured engine if only one is present)
-
-Graphs with explicit `traversalSources` entries are excluded from the implicitly defined traversal sources described in
-the previous section.
-
-===== Java-Based Lifecycle Hooks
-
-For startup and shutdown logic that goes beyond declarative configuration such as loading sample data, initializing
-caches, or custom setup, Java-based `LifeCycleHook` implementations can now replace Groovy init scripts:
-
-[source,yaml]
-----
-lifecycleHooks:
- - className: org.apache.tinkerpop.gremlin.server.util.TinkerFactoryDataLoader
- config: {graph: graph, dataset: modern}
-----
-
-Each entry specifies a `className` implementing `LifeCycleHook` and an optional `config` map passed to the hook's
-`init()` method. The built-in `TinkerFactoryDataLoader` supports datasets: `airroutes`, `modern`, `classic`, `crew`,
-`grateful`, and `sink`.
-
-===== Migrating from Groovy Init Scripts
-
-Creating `TraversalSource` and `LifeCycleHook` instances via Groovy init scripts is now deprecated. Existing scripts
-continue to work when `GremlinGroovyScriptEngine` is explicitly configured, but a deprecation warning is logged at
-startup. Support for Groovy script initialization and customization may be dropped in a future release.
-
-*Before (Groovy init script):*
-
-[source,groovy]
-----
-def globals = [:]
-globals << [hook : [
- onStartUp: { ctx ->
- org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerFactory.generateModern(graph)
- }
-] as LifeCycleHook]
-globals << [g : traversal().withEmbedded(graph)]
-----
-
-*After (YAML only):*
-
-[source,yaml]
-----
-graphs: {
- graph: conf/tinkergraph-empty.properties}
-lifecycleHooks:
- - { className: org.apache.tinkerpop.gremlin.server.util.TinkerFactoryDataLoader, config: {graph: graph, dataset: modern}}
-----
-
-The `g` binding is implicitly created from the `graph` entry. No `scriptEngines` section is needed.
-
-===== `ScriptEngine` Allowlist
-
-The `scriptEngines` configuration in the Gremlin Server YAML now acts as an allowlist. Only `ScriptEngine`
-implementations explicitly listed in the configuration will accept requests. The `gremlin-lang` `ScriptEngine` is always
-available regardless of configuration.
-
-Previously, any `GremlinScriptEngineFactory` discovered via Java's `ServiceLoader` mechanism on the classpath could be
-used by clients, even if it was not listed in the server's `scriptEngines` configuration. This meant that
-`gremlin-groovy` was always available as long as its JAR was on the classpath, regardless of the server configuration.
-
-With this change, a request specifying a `language` that is not in the `scriptEngines` configuration will receive a
-`400 Bad Request` response. Providers who rely on `gremlin-groovy` or any other `ScriptEngine` must explicitly include
-it in their `scriptEngines` configuration:
-
-[source,yaml]
-----
-scriptEngines: {
- gremlin-lang: {},
- gremlin-groovy: {
- plugins: {
- org.apache.tinkerpop.gremlin.server.jsr223.GremlinServerGremlinPlugin: {}}}}
-----
-
-See: link:https://issues.apache.org/jira/browse/TINKERPOP-2720[TINKERPOP-2720],
-link:https://issues.apache.org/jira/browse/TINKERPOP-3107[TINKERPOP-3107]
-
-==== `gremlin-lang` based Parameters
-
-Bindings/parameters that are sent as part of the request are now `gremlin-lang` string maps rather than an actual Map
-that would have been serialized based on the serializer used for the request. A side effect of this is that the map key
-must be a valid Java identifier. This means that certain items can no longer be sent like `#jsr223` control flags that
-were used for the `gremlin-groovy` ScriptEngine. Ensure that you are using valid Java identifiers (e.g. start with a
-letter, no spaces, can't use reserved keywords, etc.) for keys.
-
-Since parameters are now text-based gremlin-lang literals, `Traversal` objects can no longer be passed as binding
-values. In previous versions it was possible to pass a traversal as a parameter:
-
-[source,text]
-----
-// 3.x — no longer supported in 4.0
-client.submit("g.V(x)", Map.of("x", __.has("name","marko")));
-----
-
-This pattern is now rejected by the server as a security measure to prevent traversal injection through parameter maps.
-Traversals should be composed directly in the Gremlin query string rather than supplied as parameters.
-
-Parameter maps are also subject to a maximum nesting depth of 32 levels. Deeply nested map or collection structures
-beyond this limit will be rejected with an error.
-
-See: link:https://issues.apache.org/jira/browse/TINKERPOP-3247[TINKERPOP-3247]
-
-==== JavaScript Typed Numeric Wrappers
-
-JavaScript has a single `Number` type (IEEE 754 double) which loses the distinction between Gremlin numeric types like
-`int`, `float`, `long`, and `double`. The `gremlin-javascript` driver now provides typed wrapper classes and factory
-functions that give explicit control over how numbers are serialized and deserialized.
-
-On the *serialization* side, wrapping a value controls the GremlinLang type suffix and GraphBinary type code sent to
-the server:
-
-[source,javascript]
-----
-const { toInt, toLong, toFloat, toDouble } = gremlin.structure;
-
-g.V().has('age', toInt(29)).next(); // age sent as Int
-g.V().has('score', toFloat(3.14)).next(); // score sent as Float
-g.V().has('id', toLong('9007199254740993')).next(); // id sent as Long
-----
-
-`toLong()` accepts `number`, `string`, or `bigint`. Number inputs must be within the safe integer range (throws
-`RangeError` otherwise); string and bigint inputs support the full signed 64-bit range.
-
-Without wrappers, the driver continues to infer types automatically from the JavaScript value, so existing code is
-unaffected.
-
-On the *deserialization* side, a new `preciseNumbers: true` connection option wraps incoming numeric values in the
-same typed wrappers, preserving the server's original type information:
-
-[source,javascript]
-----
-const g = traversal().with_(new DriverRemoteConnection('http://localhost:8182/gremlin', {
- preciseNumbers: true
-}));
-
-const v = await g.V(1).elementMap().next();
-const age = v.value.get('age'); // Int { value: 29, type: 'int' }
-age + 1; // 30 — wrappers support arithmetic via valueOf()
-----
-
-The `unwrap()` helper extracts the raw value from any wrapper, passing non-wrapper values through unchanged:
-
-[source,javascript]
-----
-const { unwrap } = gremlin.structure;
-unwrap(toInt(29)); // 29
-unwrap('hello'); // 'hello'
-----
-
-==== Subgraph Support in GLVs
-
-All GLVs now support the `subgraph()` step. Previously, calling `subgraph()` from a GLV produced an unknown-type error
-because the variant could not interpret the `Graph` payload that the server returned. Applications can now extract a
-portion of a remote graph as part of a normal traversal and inspect its vertices and edges directly from the client,
-without having to re-issue queries to reconstruct the result. See: <<subgraph-step>>.
-
-In the GLVs, the result is a detached snapshot of the captured vertices and edges, not a traversable `Graph` instance.
-It cannot be passed to `traversal().with(...)`, and mutating its collections has no effect on the source graph. To
-re-query elements against the original graph, extract their ids and call `g.V(id)` or `g.E(id)` against the original
-`GraphTraversalSource`.
-
-==== Provider Defined Types
-
-Graph providers may now expose custom types as Provider Defined Types (PDT) (replacing the old `CustomTypeSerializer`
-mechanism). The key improvement is that the default case now works out of the box — drivers deserialize PDT values
-as `ProviderDefinedType` objects containing a `name` and a `fields` map without any configuration, eliminating
-the serializer errors that occurred with unknown custom types in TP3. For automatic conversion between PDT values and
-application-specific types, each driver supports an optional registry or annotation mechanism, which requires similar
-effort to the old custom serializer approach but is entirely optional for basic usage:
-
-* <<gremlin-java-pdt,Gremlin-Java>>
-* <<gremlin-python-pdt,Gremlin-Python>>
-* <<gremlin-javascript-pdt,Gremlin-JavaScript>>
-* <<gremlin-dotnet-pdt,Gremlin.Net>>
-* <<gremlin-go-pdt,Gremlin-Go>>
-
-
-==== Tree No Longer Extends HashMap
-
-`Tree` no longer extends `HashMap`. It is now a `final` class that holds a `Map` internally and exposes a
-tree-shaped API instead of `Map` methods. This is a breaking change for code that treated a `tree()` result as a
-`Map`.
-
-Replacements for the common `Map`-based access patterns:
-
-[options="header"]
-|=======================
-|3.x (`Tree` as `Map`) |4.x (`Tree` API)
-|`tree.get(key)` |`tree.childAt(key)` (throws if absent) or `tree.findSubtree(key)` (recursive, returns `Optional`)
-|`tree.containsKey(key)` |`tree.hasChild(key)`
-|`tree.keySet()` |`tree.rootNodes()`
-|`tree.size()` |`tree.rootNodes().size()` for root entries, or `tree.nodeCount()` for total nodes
-|`getObjectsAtDepth(d)` |`getNodesAtDepth(d)` (now 0-based: depth 0 returns the roots)
-|`getLeafObjects()` |`getLeafNodes()`
-|=======================
-
-A few Gremlin patterns that worked only because `Tree` was a `Map` (for example `select(keys)` and `unfold()`
-applied to a `Tree`) no longer compose. Process the `Tree` result client-side after `next()`, or reshape the
-upstream traversal.
-
-`count(local)` on a `Tree` has changed semantics. Previously, because `Tree` was a `Map`, it returned the
-number of root entries; it now returns the total number of nodes in the tree (`Tree.nodeCount()`), consistent
-with how `count(local)` counts the contents of other local objects (for example the objects in a `Path`). Use
-`rootNodes().size()` on the materialized `Tree` if the root-entry count is required.
-
-`isLeaf()` no longer throws on an empty tree (it returns `true`), and a `Tree` keeps the long-standing limitation
-that sibling branches resolving to the same value collapse into one node; use `path()` or `subgraph()` when full
-path structure must be preserved.
-
-See: link:https://lists.apache.org/thread/o0nqh6kmrkdht531655p351ldjll045d[[DISCUSS] Make Tree no longer extend HashMap]
-
-
-=== Upgrading for Providers
-
-==== Graph System Providers
-
-===== Provider Defined Types
-
-TinkerPop 4 replaces the TP3 `CustomTypeSerializer` mechanism with Provider Defined Types (PDT). The TP3 extension
-point has been removed entirely and there is no backward-compatible bridge, so any existing `CustomTypeSerializer`
-implementations must be migrated: providers expose their custom types by annotating classes with `@ProviderDefined`
-or, for types they don't own, by implementing `ProviderDefinedTypeAdapter<T>`. Adapters are discovered automatically
-via ServiceLoader, so this requires similar effort to the old approach.
-
-The key improvement is that driver users now receive PDT values as structured `ProviderDefinedType` objects by
-default, without any configuration — eliminating the serializer errors that unknown custom types caused in TP3, and
-benefiting all driver users transparently.
-
-See <<provider-defined-types>> for full details on annotation usage, field filtering, nested types, and ServiceLoader
-registration.
-
-`Tree` no longer extends `HashMap`. Provider code that inspected or rebuilt a `Tree` via `Map` methods
-(`get`, `put`, `keySet`, `entrySet`, `size`) must use the tree-shaped API instead: read with `rootNodes()` +
-`childAt(key)` and build with `getOrCreateChild(key)` + `addTree(subtree)`. The GraphSON (`g:Tree`) and
-GraphBinary (`0x2b`) wire formats are unchanged, so no GraphSON- or GraphBinary-serialized data or cross-version
-===== Tree Serialization and API Changes
-
-`Tree` no longer extends `HashMap`.
-
-Providers that use the reference (de)serializers receive a `Tree` instance from TinkerPop. Code that inspected or
-rebuilt that `Tree` via `Map` methods (`get`, `put`, `keySet`, `entrySet`, `size`) must use the tree-shaped API
-instead: read with `rootNodes()` + `childAt(key)` and build with `getOrCreateChild(key)` + `addTree(subtree)`.
-
-The GraphSON (`g:Tree`) and GraphBinary (`0x2b`) wire formats are unchanged, so no GraphSON- or GraphBinary-serialized data or cross-version
-compatibility is affected. The Gryo `Tree` wire format, however, did change: in 3.x a `Tree` was serialized via
-Kryo's default `Map` serializer because it extended `HashMap`, whereas in 4.x it has an explicit `Tree`
-serializer. As a result, Gryo-serialized `Tree` data written by 3.x cannot be read by 4.x and vice versa. The
-Gryo type registration id (`61`) is unchanged and 4.x-to-4.x Gryo round-trips correctly; this Gryo break is
-expected for the 4.0.0 major release.
-
-==== Graph Driver Providers
-
-===== Request Interceptors
-
-Graph driver providers should implement request interceptor support in their drivers. Interceptors allow users to
-modify the HTTP request before it is sent, which is essential for authentication schemes (like SigV4), adding
-provider-specific request fields, and other server-specific capabilities.
-
-All TinkerPop reference drivers now include interceptor support. The interceptor contract is standardized across all
-GLVs: interceptors receive a mutable HTTP request object, can modify headers/body/URI, and the driver auto-serializes
-the request body to JSON after all interceptors have run.
-
-For the full specification of how interceptors should behave, see the
-link:https://tinkerpop.apache.org/docs/x.y.z/dev/provider/#_http_request_interceptor[HTTP Request Interceptor]
-section in the provider documentation.
-
-===== match() Support
-
-The new `match(String)` step represents TinkerPop's first explicit extension point for provider-native query languages.
-Graph systems that support a declarative query language can now expose it directly through the standard Gremlin
-traversal API, making the language a first-class citizen of any `g.` chain rather than a parallel API that users have to
-context-switch into.
-
-The mechanism follows the same provider extension pattern used elsewhere in TinkerPop: `gremlin-core` inserts a
-placeholder step (`DeclarativeMatchStep`) into the traversal, and graph providers replace it with a concrete
-implementation via a `ProviderOptimizationStrategy`. The placeholder carries everything the provider needs:
-
-* `getMatchQuery()` — the raw query string as written by the user
-* `getParams()` — the bound parameter map from the `match(String, Map)` overload, or `null`
-* `getQueryLanguage()` — the explicit language hint from `with("queryLanguage", ...)`, or `null` meaning "use your native language"
-* `isStart()` — `true` when the step was invoked as a spawn step on `GraphTraversalSource`
-
-For each result row the concrete step must:
-
-* Set the traverser value to a `Map<String, Object>` keyed by named variable name, containing one entry per bound
- variable in the row. Anonymous elements must not appear in the map.
-* Record each named variable in the traverser's path history via `addLabels()`, so downstream `select()` steps
- can retrieve values by name.
-* Declare `TraverserRequirement.LABELED_PATH` in `getRequirements()`.
-
-Providers that want to use TinkerPop's built-in GQL engine rather than supplying their own step can add the
-`gql-gremlin` module and register `GqlDeclarativeMatchStrategy.instance()` in their graph's global strategy
-cache. The singleton lazily allocates a `DefaultGqlPlanner` and `DefaultGqlExecutor` per graph instance on
-first use and caches them for the lifetime of the graph, sharing the planner's query parse cache across all
-traversals. Optional performance hints are available via `countVerticesByLabel()`, `countEdgesByLabel()`,
-and `Graph.Index`. See `GqlMatchStep` and `GqlDeclarativeMatchStrategy` in `gql-gremlin` for the complete
-reference implementation, and the
-link:https://tinkerpop.apache.org/docs/x.y.z/dev/provider/#tinkerpop-providers-tinkergql[provider documentation]
-for wiring instructions.
-
-== TinkerPop 4.0.0-beta.2
-
-*Release Date: April 1, 2026*
-
-Please see the link:https://github.com/apache/tinkerpop/blob/4.0.0-beta.2/CHANGELOG.asciidoc#release-4-0-0-beta-2[changelog] for a
-complete list of all the modifications that are part of this release.
-
-=== Upgrading for Users
-
-==== Python Property Access
-
-The `Element` class in `gremlin-python` now supports `__contains__` and `keys()`, enabling more idiomatic Python
-patterns for working with element properties. You can now use the `in` operator to check for property existence and
-`keys()` to retrieve the set of property names:
-
-[source,python]
-----
-v = g.V().has('person','name','stephen').next()
-
-# check if a property exists
-if "age" in v:
- print(v["age"])
-
-# get all property keys
-print(v.keys()) # {'name', 'age'}
-----
-
-See: link:https://issues.apache.org/jira/browse/TINKERPOP-3119[TINKERPOP-3119]
-
-==== Runtime Upgrades
-
-All JavaScript projects (`gremlin-javascript`, `gremlin-mcp`, `gremlint`) have been upgraded to node version 22.
-
-==== ResultQueue Removed
-
-The public class `ResultQueue` in `gremlin-driver` has been removed. Its functionality has been merged into
-`ResultSet`. Users of this class should reference the newly added methods of `ResultSet` instead.
-
-==== neo4j-gremlin Removed
-
-The module `neo4j-gremlin` was deprecated in 3.7.0 and has now been removed. It was based on version 3.4 of Neo4j which
-reached EOL in March 2020. Users that depend on this module will need to stay on the 3.x line.
-
-==== Gremlin MCP Server
-
-===== Gremlin Query Translation
-
-A `translate_gremlin_query` tool is now available that translates a Gremlin query into a target language variant.
-Supported targets are `canonical`, `javascript`, `python`, `go`, `dotnet`, `java`, `groovy`, and `anonymized`.
-
-The optional `source` parameter describes the dialect of the input. When omitted or set to `auto`, the server
-normalizes the input before translating — first by applying mechanical transformations (stripping language-specific
-prefixes, correcting step casing, etc.) and then by requesting LLM normalization from the MCP client via MCP
-sampling. If the MCP client does not support sampling, the LLM step is skipped gracefully and a warning is included
-in the response. Set `source` to `canonical` to bypass normalization entirely when the input is already in canonical
-gremlin-language ANTLR format.
-
-Some example prompts that will invoke this tool:
-
-[source,text]
-----
-Translate g.V().has('name','Alice').out('knows').values('name') to Python.
-----
-
-[source,text]
-----
-Convert this Go Gremlin traversal to Groovy:
-gremlingo.T__.V().Has("name", "Alice").Out("knows").Values("name")
-----
-
-[source,text]
-----
-I have some Java Gremlin code. Translate it to canonical format so I can review it:
-g.V().has("name", "Alice").out("knows").values("name")
-----
-
-===== Offline Mode
-
-`GREMLIN_MCP_ENDPOINT` is no longer required to start the server. When no endpoint is configured, graph tools
-(`get_graph_status`, `get_graph_schema`, `run_gremlin_query`) are not registered, but the utility tools
-(`translate_gremlin_query`, `format_gremlin_query`) remain fully available. This makes it possible to use the
-Gremlin MCP Server purely as a translation and formatting aid without any graph database:
-
-[source,text]
-----
-Format this Gremlin query for readability:
-g.V().has('name','Alice').out('knows').out('knows').where(neq('Alice')).values('name').dedup()
-----
-
-==== SLF4j 2.x
-
-TinkerPop has generally upgraded to SLF4j 2.x which brings with it some important changes to log initialization which
-may affect user applications that are upgrading from TinkerPop 3.x. Please see the
-link:https://www.slf4j.org/faq.html[SLF4j FAQ] (specifically "What has changed in SLF4J version 2.0.0?") that explains
-the differences and how they might apply.
-
-[[canonical-gremlin]]
-==== Canonical Gremlin
-
-In previous versions, GLV drivers sent traversals to the server as serialized `Bytecode` objects. In 4.0, `Bytecode`
-has been replaced by `GremlinLang`, which produces a canonical Gremlin string along with a map of named parameters.
-"Canonical Gremlin" is the standard, language-neutral string representation of a traversal as defined by the ANTLR
-grammar in the `gremlin-language` module. Each GLV now builds this canonical string directly, and the server's
-`gremlin-lang` script engine parses it using the same grammar.
-
-This change means all drivers speak the same language on the wire. Request payloads are now human-readable strings
-rather than opaque binary bytecode, making it easier to debug, log, and reason about what is being sent to the server.
-When documentation or code refers to a "gremlin-lang string", "canonical Gremlin", or "canonical format", it means a
-traversal string that conforms to this ANTLR grammar.
-
-For a detailed explanation of canonical Gremlin with examples in each language, see
-link:https://tinkerpop.apache.org/docs/4.0.0-beta.2/reference/#canonical-gremlin-definition[Canonical Gremlin and GremlinLang]
-in the Reference Documentation.
-
-[[glv-driver-changes]]
-==== GLV Driver Changes
-
-All Gremlin Language Variant drivers have been updated with three major changes in TinkerPop 4.0:
-
-1. *WebSockets replaced by HTTP* — All drivers now communicate with Gremlin Server over HTTP/1.1 using POST requests.
- WebSocket-specific settings and classes have been removed. Connection URLs change from `ws://` to `http://` (or
- `wss://` to `https://`). HTTP connection pooling is handled by each language's standard HTTP library.
-
-2. *Bytecode replaced by GremlinLang* — Traversals are no longer serialized as `Bytecode` objects. Instead, each GLV
- produces a <<canonical-gremlin, canonical Gremlin>> string via `GremlinLang`, which is sent to the server along with
- a parameter map. This simplifies the wire protocol and makes request payloads human-readable.
-
-3. *Interceptor-based authentication* — With the move to HTTP, authentication is now handled per-request through
- HTTP headers rather than during a connection handshake. All drivers use request interceptors to add auth headers
- before each request is sent. Built-in interceptors are provided for two common scenarios:
- - `BasicAuth` — adds a standard HTTP Basic `Authorization` header (username/password). This replaces the previous
- constructor parameters or SASL authenticators used in 3.x.
- - `SigV4Auth` — signs requests using AWS Signature Version 4. The interceptor handles credential resolution
- (including automatic refresh for temporary credentials) and request signing transparently.
- Custom interceptors can also be written to support other authentication schemes your graph provider may require.
-
-The .NET, Go, and JavaScript drivers are new to 4.0 in this release. The Java and Python drivers were updated in the
-beta.1 release and are summarized at the end of this section; see the <<java-requestinterceptor, Java>> and
-<<python-requestinterceptor, Python>> sections in the beta.1 upgrade notes for full details.
-
-[[dotnet-http-interceptor]]
-==== .NET
-
-The .NET driver (`Gremlin.Net`) has been updated to use HTTP. Connection URLs should be updated from `ws://` to
-`http://` (or `wss://` to `https://`). The following settings have changed:
-
-- `ConnectionPoolSettings` — replaced with `ConnectionSettings` for HTTP connection configuration.
-- `webSocketConfiguration` — removed.
-- `sessionId` — removed.
-- `disableCompression` — removed. Use `ConnectionSettings.EnableCompression` instead.
-- `username` and `password` on `GremlinServer` — removed.
-- `requestSerializer` and `responseSerializer` — can now be set independently on `GremlinClient`.
-- `GraphBinaryMessageSerializer` — replaced with `GraphBinary4MessageSerializer`.
-- `ConnectionPool` and `WebSocketConnection` — removed. HTTP connection pooling is managed by `SocketsHttpHandler`.
-- Transaction support over HTTP is not yet implemented and `Tx()` will throw `NotSupportedException`.
-
-Authentication in 3.x was configured with `username` and `password` on the `GremlinServer` constructor. In 4.0, use
-the `Auth` static methods via the `interceptors` parameter instead:
-
-[source,csharp]
-----
-// 3.x — credentials on GremlinServer (no longer supported)
-// var server = new GremlinServer("localhost", 8182, true, "username", "password");
-
-// 4.0 — Basic authentication via interceptor
-var server = new GremlinServer("localhost", 8182, enableSsl: true);
-var client = new GremlinClient(server,
- connectionSettings: new ConnectionSettings { SkipCertificateValidation = true },
- interceptors: new[] { Auth.BasicAuth("username", "password") });
-
-// 4.0 — SigV4 authentication via interceptor
-var server = new GremlinServer("localhost", 8182, enableSsl: true);
-var client = new GremlinClient(server,
- interceptors: new[] { Auth.SigV4Auth("service-region", "service-name") });
-----
-
-Setting `requestSerializer` to `null` prevents the `RequestMessage` from being serialized before interceptors run,
-allowing an interceptor to handle serialization and set the `Content-Type` header directly.
-
-[[go-http-interceptor]]
-==== Go
-
-The Go driver (`gremlin-go`) has been updated to use HTTP. Connection URLs should be updated from `ws://` to
-`http://` (or `wss://` to `https://`). The following settings have changed:
-
-- `AuthInfo` — removed.
-- `TransporterType`, `ReadBufferSize`, `WriteBufferSize`, `WriteDeadline`, `NewConnectionThreshold` — removed.
-- `Session` — removed.
-- `MaximumConcurrentConnections`, `MaxIdleConnections`, `IdleConnectionTimeout`, `KeepAliveInterval` — added for HTTP
- connection pool configuration.
-
-Authentication in 3.x was configured with the `AuthInfo` setting. In 4.0, use the `BasicAuth()` and `SigV4Auth()`
-interceptors instead:
-
-[source,go]
-----
-// 3.x — AuthInfo setting (no longer supported)
-// settings.AuthInfo = gremlingo.BasicAuthInfo("username", "password")
-
-// 4.0 — Basic authentication via interceptor
-remote, err := gremlingo.NewDriverRemoteConnection("https://localhost:8182/gremlin",
- func(settings *gremlingo.DriverRemoteConnectionSettings) {
- settings.RequestInterceptors = []gremlingo.RequestInterceptor{
- gremlingo.BasicAuth("username", "password"),
- }
- })
-
-// 4.0 — SigV4 authentication via interceptor
-remote, err := gremlingo.NewDriverRemoteConnection("https://localhost:8182/gremlin",
- func(settings *gremlingo.DriverRemoteConnectionSettings) {
- settings.RequestInterceptors = []gremlingo.RequestInterceptor{
- gremlingo.SigV4Auth("service-region", "service-name"),
- }
- })
-----
-
-[[javascript-typescript-esm]]
-==== JavaScript
-
-The JavaScript driver (`gremlin-javascript`) has been rewritten in TypeScript, migrated to HTTP, and now ships with
-built-in type declarations and dual ESM/CommonJS builds. Connection URLs should be updated from `ws://` to `http://`
-(or `wss://` to `https://`). The following settings have changed:
-
-- `mimeType` — removed. Use `reader` and `writer` options directly.
-- `authenticator` — removed.
-- `session` — removed.
-- `interceptors` — added to `Client` and `DriverRemoteConnection` for HTTP request modification.
-- `writer` — can be set to `null` to skip request serialization, allowing interceptors to handle it directly.
-- `bulkResults` — added as a request option. `DriverRemoteConnection` defaults it to `true`.
-
-Authentication in 3.x was configured with the `authenticator` option. In 4.0, use `auth.basic()` and `auth.sigv4()`
-instead:
-
-[source,javascript]
-----
-import gremlin from 'gremlin';
-const { DriverRemoteConnection, auth } = gremlin.driver;
-
-// 3.x — PlainTextSaslAuthenticator (no longer supported)
-// const authenticator = new gremlin.driver.auth.PlainTextSaslAuthenticator('user', 'pass');
-// new DriverRemoteConnection('ws://localhost:8182/gremlin', { authenticator });
-
-// 4.0 — Basic authentication via interceptor
-const connection = new DriverRemoteConnection('https://localhost:8182/gremlin', {
- interceptors: auth.basic('username', 'password'),
-});
-
-// 4.0 — SigV4 authentication via interceptor
-// Requires @smithy/signature-v4 and @smithy/hash-node packages
-const connection = new DriverRemoteConnection('https://localhost:8182/gremlin', {
- interceptors: auth.sigv4('service-region', 'service-name'),
-});
-----
-
-===== TypeScript and Module Format
-
-The package now sets `"type": "module"` in `package.json` and uses conditional `exports`:
-
-- ESM: `import gremlin from 'gremlin'` resolves to `build/esm/index.js`
-- CJS: `const gremlin = require('gremlin')` resolves to `build/cjs/index.cjs`
-
-Existing CommonJS applications using `require('gremlin')` continue to work without changes:
-
-[source,javascript]
-----
-// CommonJS (still works)
-const gremlin = require('gremlin');
-
-// ESM — default import
-import gremlin from 'gremlin';
-
-// ESM — named imports
-import { driver, process, structure } from 'gremlin';
-----
-
-Type declarations (`.d.ts`) are included in the published package. TypeScript projects can import the driver directly
-without installing separate `@types` packages:
-
-[source,typescript]
-----
-import gremlin from 'gremlin';
-import type { ConnectionOptions } from 'gremlin/build/esm/driver/connection.js';
-
-const connection = new gremlin.driver.DriverRemoteConnection('http://localhost:8182/gremlin');
-const g = gremlin.process.traversal().with_(connection);
-----
-
-===== Breaking Export Changes
-
-Several exports have been removed or renamed compared to 3.x:
-
-- `process.Bytecode` — removed. Use `process.GremlinLang` instead.
-- `process.Translator` — removed. Use `process.GremlinLang` instead (e.g. `traversal.getGremlinLang().getGremlin()`).
-- `driver.auth.Authenticator` and `driver.auth.PlainTextSaslAuthenticator` — removed. Use `driver.auth.basic()` and
- `driver.auth.sigv4()` instead.
-- `structure.io` — removed. Serialization is now internal to the driver.
-- `Graph.traversal()` — removed. Use `process.traversal()` instead.
-
-==== Java
-
-The Java driver (`gremlin-driver`) was the first to adopt HTTP in the beta.1 release. Connection URLs should be
-updated from `ws://` to `http://` (or `wss://` to `https://`). The following settings have changed:
-
-- `enableCompression` — removed.
-- `bulkResults` — added. See <<result-bulking-from-server, Result Bulking from Server>> for details.
-- `maxContentLength` — renamed to `maxResponseContentLength`. Now limits total response size.
-- `minConnectionPoolSize` — removed. Connections are now closed based on `idleConnectionTimeout` rather than usage
- thresholds. Multiple connections can be opened concurrently to support bursty workloads.
-
-Authentication in 3.x was configured with `credentials()` on the `Cluster` builder. In 4.0, pass `Auth.basic()` or
-`Auth.sigv4()` to the builder's `auth()` method instead:
-
-[source,java]
-----
-// 3.x — credentials on Cluster builder (no longer supported)
-// Cluster cluster = Cluster.build("localhost").credentials("username", "password").create();
-
-// 4.0 — Basic authentication
-Cluster cluster = Cluster.build("localhost").auth(Auth.basic("username", "password")).create();
-
-// 4.0 — SigV4 authentication
-Cluster cluster = Cluster.build("localhost").auth(Auth.sigv4("service-region", "service-name")).create();
-----
-
-For advanced use cases, HTTP interceptors can be configured on `Cluster` using `addInterceptor`,
-`addInterceptorBefore`, `addInterceptorAfter`, and `removeInterceptor`. Each interceptor requires a name for ordering
-and receives an `HttpRequest` containing the request method, URI, headers, and body. A default "serializer"
-interceptor handles serialization of the `RequestMessage` into the format the server expects.
-
-[source,java]
-----
-Cluster cluster = Cluster.build("localhost")
- .addInterceptor("myAuth", request -> {
- request.getHeaders().put("Authorization", "Bearer my-token");
- return request;
- })
- .create();
-----
-
-==== Python
-
-The Python driver (`gremlin-python`) adopted HTTP in the beta.1 release. Connection URLs should be updated from
-`ws://` to `http://` (or `wss://` to `https://`). The following settings have changed:
-
-- `enableCompression` — removed.
-- `bulk_results` — added. See <<result-bulking-from-server, Result Bulking from Server>> for details.
-- `message_serializer` — split into `request_serializer` and `response_serializer`.
-- `username` and `password` — replaced with `auth`.
-- `kerberized_service` — removed.
-- `session` — removed.
-
-Authentication in 3.x was configured with `username` and `password` parameters on `DriverRemoteConnection`. In 4.0,
-use the `auth` parameter with `basic()` or `sigv4()` from the `auth` module instead:
-
-[source,python]
-----
-from gremlin_python.driver.auth import basic, sigv4
-
-# 3.x — username/password parameters (no longer supported)
-# g = traversal().with_(DriverRemoteConnection('ws://localhost:8182/gremlin', 'g',
-# username='stephen', password='password'))
-
-# 4.0 — Basic authentication
-g = traversal().with_(DriverRemoteConnection(
- 'http://localhost:8182/gremlin', 'g', auth=basic('stephen', 'password')))
-
-# 4.0 — SigV4 authentication
-g = traversal().with_(DriverRemoteConnection(
- 'http://localhost:8182/gremlin', 'g', auth=sigv4('service-region', 'service-name')))
-----
-
-HTTP interceptors can be passed to `DriverRemoteConnection` or `Client` using the `interceptors` parameter. An
-interceptor is a `Callable` that receives the HTTP request dictionary (containing headers, payload, and auth). Setting
-`request_serializer` to `None` prevents automatic serialization, allowing an interceptor to handle it directly.
-
-==== Transactions Re-enabled
-
-IMPORTANT: The remote transaction API is still under active discussion and the specification has not been finalized.
-This implementation is experimental and subject to breaking changes in future releases. It is provided to enable early
-feedback and testing, but should not be relied upon for production use until the specification is complete.
-
-The 4.0.0-beta.1 release disabled transactions and noted that `tx()` would return an error. Transactions have now been
-re-enabled over HTTP for both Gremlin Server and the Java driver. The transaction model uses server-managed sessions
-where each transaction is identified by a server-generated transaction ID that the client passes on subsequent requests.
-
-The basic lifecycle is: begin a transaction, submit one or more traversals within it, then commit or rollback. Data
-written inside a transaction is isolated from other clients until committed.
-
-Transactions also work through `DriverRemoteConnection` with the familiar `g.tx()` pattern:
-
-[source,java]
-----
-final GraphTraversalSource g = traversal().with(DriverRemoteConnection.using(cluster, "g"));
-final GraphTraversalSource gtx = g.tx().begin();
-gtx.addV("person").iterate();
-gtx.tx().commit();
-----
-
-The `RemoteTransaction` can be used directly from `Cluster.transact()`:
-
-[source,java]
-----
-final Cluster cluster = Cluster.open();
-
-// begin, write, and commit
-final RemoteTransaction tx = cluster.transact("g");
-tx.begin();
-tx.submit("g.addV('person').property('name','alice')");
-tx.commit();
-----
-
-The `RemoteTransaction` also supports configurable close behavior. By default, `close()` commits the transaction. To
-rollback on close instead:
-
-[source,java]
-----
-final RemoteTransaction tx = cluster.transact("g");
-tx.onClose(Transaction.CLOSE_BEHAVIOR.ROLLBACK);
-tx.begin();
-tx.submit("g.addV('person')");
-tx.close(); // rolls back instead of committing
-----
-
-NOTE: The current implementation creates a dedicated HTTP connection pool per transaction. Connection sharing between
-requests will be improved in the final release for better resource efficiency and performance.
-
-=== Upgrading for Providers
-
-==== Graph System Providers
-
-===== Java-based Test Suite
-
-The traditional Java-based "process" test suite has been removed. It was deprecated in 3.8.0, with the instruction to
-move to the more comprehensive, language agnostic, Gherkin test framework which now unifies all Gremlin semantics
-testing. This unified approach to testing with Gherkin provides the easiest way to ensure that the same Gremlin
-semantics are applied for both graph systems and for Gremlin Language Variants, with the additional benefit that its
-easy-to-read format is well suited to LLMs.
-
-TinkerPop does retain a small cohort of Java-based "process" tests for embedded graphs wishing to validate some
-additional features that are not well suited to the Gherkin style. Providers who wish to use these simply implement the
-`ProcessEmbeddedStandardSuite` and the `ProcessEmbeddedComputerSuite` as has normally been done in the past.
-
-== TinkerPop 4.0.0-beta.1
-
-*Release Date: January 17, 2025*
-
-Please see the link:https://github.com/apache/tinkerpop/blob/4.0.0-beta.1/CHANGELOG.asciidoc#release-4-0-0-beta-1[changelog] for a
-complete list of all the modifications that are part of this release.
-
-NOTE: 4.0.0-beta.1 is a beta/milestone release. It is meant as a preview version to try out the new HTTP API
-features in the server and drivers (Java/Python only). As this is a beta version only, you can expect breaking changes to
-occur in future betas for 4.0.0 on the way to its General Availability release. Items that have important
-limitations and constraints pertinent to this beta will be highlighted through the documentation inside an
-"IMPORTANT" box that starts with "4.0 Beta Release".
-
-=== Upgrading for Users
-
-[[result-bulking-from-server]]
-==== Result Bulking from Server
-In previous versions, when a traversal is submitted through the DriverRemoteConnection (DRC) via the Bytecode processor,
-the results from the server were bulked as Traverser, which provides a form of result optimization across the wire.
-Starting with 4.0, with the removal of Bytecode and Traverser serializer, this optimization is now achieved via
-`GraphBinaryV4` response message serialization, and can be controlled through cluster setting or per request option.
-
-Per request option setting will always override cluster settings, and regardless of cluster or request option settings,
-bulking will only occur if the script processing language is set to `gremlin-lang` and the serializer is set to `GraphBinaryV4`.
-
-[source,java]
-----
-// cluster setting
-Cluster cluster = Cluster.build().bulkResults(true).create();
-
-// per request option
-GraphTraversalSource g = traversal().with(DriverRemoteConnection.using(cluster));
-List result = g.with("language", "gremlin-lang").with("bulkResults", true).inject(1).toList();
-----
-
-By default, the cluster setting of `bulkResults` is false. To remain consistent with previous behavior, remote traversal
-submitted through the DRC will always send a request option setting `bulkResults` to `true`. This implies that if `gremlin-lang`
-script engine and `GraphBinaryV4` serializer are used, then server will bulk results before sending regardless of cluster setting,
-and can only be disabled via per request option.
-
-==== BulkSet Behavior Changes
-Starting with 4.0, steps which return BulkSet (e.g. `aggregate()`) will have results returned in different format
-depending on embedded or remote usage.
-
-For embedded cases, a BulkSet will be returned as before.
-
-For remote cases, BulkSets will now be expanded into Lists upon deserialization with `gremlin-driver`. All other GLVs
-already expanded BulkSet to List prior to TinkerPop 4. Each element in the BulkSet will appear in the list the same
-number of times as specified by its bulk value.
-
-==== Configuration Changes
-
-The following configuration changes were introduced in the beta.1 release for Gremlin Server, Java, and Python. For
-.NET, Go, and JavaScript configuration changes, see <<glv-driver-changes, GLV Driver Changes>> in the section above.
-
-* Gremlin Server
-** `maxContentLength` setting has been renamed to `maxRequestContentLength`.
-* Java GLV
-** `enableCompression` setting has been removed.
-** `bulkResults` has been added. See <<result-bulking-from-server, result bulking>> for more details.
-** `maxContentLength` setting has been renamed to `maxResponseContentLength` and now blocks incoming responses that are
-too large based on total response size.
-** `addInterceptorAfter`, `addInterceptorBefore`, `addInterceptor` and `removeInterceptor` have been added.
-See <<java-requestinterceptor, Changes to Java RequestInterceptor>> for more details.
-* Python GLV
-** `enableCompression` setting has been removed.
-** `bulk_results` has been added. See <<result-bulking-from-server, result bulking>> for more details.
-** `interceptors` has been added to the Python GLV to modify HTTP requests. See
-<<python-requestinterceptor, Addition of Python interceptor>> for more details.
-** `message_serializer` setting has been separated into `request_serializer` and `response_serializer`. See
-<<python-requestinterceptor, Addition of Python interceptor>> for more details.
-** `username` and `password` settings for the Python GLV has been replaced with `auth`.
-** `kerberized_service` setting has been removed.
-** `session` setting has been removed.
-
-==== Console Command Removals
-
-The `:remote` and `:submit` commands, used to establish connections and send scripts to a remote `gremlin-server`, are
-no longer supported in `gremlin-console`. If sending a traversal, users should instead create a `RemoteTraversalSource`
-(see <<simplified-g-creation, Simplification to g Creation for examples>>).
-
-While a `RemoteTraversalSource` is the preferred method of executing remote traversals from `gremlin-console`, it
-remains possible to send scripts directly using a `gremlin-driver` `Client`.
-
-[source,groovy]
-----
-cluster = Cluster.open('conf/remote.yaml')
-client = cluster.connect()
-
-client.submit("g.V()")
-
-client.close()
-cluster.close()
-----
-
-==== Removal of Gephi Console Plugin
-
-The Gephi Plugin for `gremlin-console` is no longer supported and has been removed. Apache TinkerPop no longer maintains
-any graph visualization tool, however there are a number of community-led alternatives available, many of which are
-listed on the link:https://tinkerpop.apache.org/community.html#powered-by[TinkerPop community page].
-
-[[java-requestinterceptor]]
-==== Java RequestInterceptor
-
-Because the underlying transport has been changed from WebSockets to HTTP, the usage of the `RequestInterceptor` has
-changed as well. The `RequestInterceptor` will now be run per request and will allow you to completely modify the HTTP
-request that is sent to the server. `Cluster` has four new methods added to it: `addInterceptorAfter`,
-`addInterceptorBefore`, `removeInterceptor` and `addInterceptor`. Each interceptor requires a name as it will be used
-to insert new interceptors in different positions.
-
-The interceptors work with a new class called HttpRequest. This is just a basic abstraction over a request but it also
-contains some useful strings for common headers. The initial `HttpRequest` that is passed to the first interceptor will
-contain a `RequestMessage`. `RequestMessage` is immutable and only certain keys can be added to them. If you want to
-customize the body by adding other fields, you will need to make a different copy of the `RequestMessage` or completely
-change the body to contain a different data type. The final interceptor must return a `HttpRequest` whose body contains
-a `byte[]`.
-
-After the initial HTTP request is generated, the interceptors will be called in order to allow the request to be
-modified. After each `RequestInterceptor` is run, the request is updated with the data from the final `HttpRequest` and
-that is sent to the endpoint. There is a default interceptor added to every `Cluster` called "serializer". This
-interceptor is responsible for serializing the request body is which what the server normally expects. This is intended
-to be an advanced customization technique that should only be used when needed.
-
-[[python-requestinterceptor]]
-==== Python Interceptor
-
-HTTP interceptors have been added to `gremlin-python` to enable capability similar to that of Java GLV. These
-interceptors can be passed into either a `DriverRemoteConnection` or a `Client` using the interceptors parameter. An
-interceptor is a `Callable` that accepts one argument which is the HTTP request (dictionary containing header, payload
-and auth) or a list/tuple of these functions. The interceptors will run after the request serializer has run but before
-any auth functions run so the HTTP request may still get modified after your interceptors are run. In situations where
-you don't want the payload to be serialized, the `message_serializer` has been split into a `request_serializer` and a
-`response_serializer`. Simply set the `request_serializer` to `None` and this will prevent the `RequestMessage` from
-being serialized. Again, this is expected to be an advanced feature so some knowledge of implementation details will be
-required to make this work. For example, you'll need to know what payload formats are accepted by `aiohttp` for the
-request to be sent.
-
-==== JavaScript Set Deserialization
-
-Starting from this version, `gremlin-javascript` will deserialize `Set` data into an ECMAScript 2015 `Set`. Previously,
-these were deserialized into arrays.
-
-==== Gremlin Grammar Changes
-
-A number of changes have been introduced to the Gremlin grammar to help make it be more consistent and easier to use.
-
-*`new` keyword is now optional*
-
-The `new` keyword is now optional in all cases where it was previously used. Both of the following examples are now
-valid syntax with the second being the preferred form going forward:
-
-[source,groovy]
-----
-g.V().withStrategies(new SubgraphStrategy(vertices: __.hasLabel('person')))
-
-g.V().withStrategies(SubgraphStrategy(vertices: __.hasLabel('person')))
-----
-
-In a future version, it is likely that the `new` keyword will be removed entirely from the grammar.
-
-*Refined variable support*
-
-The Gremlin grammar allows variables to be used in various places. Unlike Groovy, from which the Gremlin grammar is
-partially derived and which allows variables to be used for any argument to a method, Gremlin only allows for variables
-to be used when they refer to particular types. In making this change it did mean that all enums like, `Scope`, `Pop`,
-`Order`, etc. can no longer be used in that way and can therefore only be recognized as literal values.
-
-*Supports withoutStrategies()*
-
-The `withoutStrategies()` configuration step is now supported syntax for the grammar. While this option is not commonly
-used it is still a part of the Gremlin language and there are times where it is helpful to have this fine grained
-control over how a traversal works.
-
-[source,groovy]
-----
-g.V().withoutStrategies(CountStrategy)
-----
-
-See: link:https://issues.apache.org/jira/browse/TINKERPOP-2862[TINKERPOP-2862],
-link:https://issues.apache.org/jira/browse/TINKERPOP-3046[TINKERPOP-3046]
-
-==== Renamed none() to discard()
-
-The `none()` step, which was primarily used by `iterate()` to discard traversal results in remote contexts, has been
-renamed to `discard()`. In its place is a new list filtering step `none()`, which takes a predicate as an argument and
-passes lists with no elements matching the predicate.
-
-==== Integer Overflow Handling
-
-Integer overflows caused by addition and multiplication operations will throw an exception instead of being silently
-skipped with incorrect result.
-
-==== SeedStrategy Construction
-
-The `SeedStrategy` public constructor has been removed for Java and has been replaced by the builder pattern common
-to all strategies. This change was made to ensure that the `SeedStrategy` could be constructed in a consistent manner.
-
-==== Removal of `gremlin-archetype`
-
-`gremlin-archetype`, which contained example projects demonstrating the use cases of TinkerPop, has been removed in
-favor of newer sample applications which can be found in each GLV's `examples` folder.
-
-==== Improved Translators
-
-The various Java `Translator` implementations allowing conversion of Gremlin traversals to string forms in various
-languages have been modified considerably. First, they have been moved from to the
-`org.apache.tinkerpop.gremlin.language.translator` package, because they now depend on the ANTLR grammar in
-`gremlin-language` to handled the translation process. Making this change allowed for a more accurate translation of
-Gremlin that doesn't need to rely on reflection and positional arguments to determine which step was intended for use.
-
-Another important change was the introduction of specific translators for Groovy and Java. While Groovy translation
-tends to work for most Java cases, there is syntax specific to Groovy where it does not. With a specific Java
-translator, the translation process can be more accurate and less error prone.
-
-The syntax for the translators has simplified as well. The translator function now takes a Gremlin string and a target
-language to translate to. Consider the following example:
-
-[source,text]
-----
-gremlin> GremlinTranslator.translate("g.V().out('knows')", Translator.GO)
-==>g.V().Out("knows")
-----
-
-Further note that Gremlin language variants produce <<canonical-gremlin, canonical Gremlin>> strings directly since
-bytecode was removed. As a result, all translators in .NET, Python, Go and Javascript have been removed.
-
-See: link:https://issues.apache.org/jira/browse/TINKERPOP-3028[TINKERPOP-3028]
-
-==== Python OptionsStrategy
-
-The `\\__init__()` syntax has been updated to be both more pythonic and more aligned to the `gremlin-lang` syntax.
-Previously, `OptionsStrategy()` took a single argument `options` which was a `dict` of all options to be set.
-Now, all options should be set directly as keyword arguments.
-
-For example:
-
-[source,python]
-----
-# 3.7 and before:
-g.with_strategies(OptionsStrategy(options={'key1': 'value1', 'key2': True}))
-# 4.x and newer:
-g.with_strategies(OptionsStrategy(key1='value1', key2=True))
-
-myOptions = {'key1': 'value1', 'key2': True}
-# 3.7 and before:
-g.with_strategies(OptionsStrategy(options=myOptions))
-# 4.x and newer:
-g.with_strategies(OptionsStrategy(**myOptions))
-----
-
-==== Custom Traversal Strategy Construction
-
-Traversal strategy construction has been updated such that it is no longer required to have concrete classes for each
-strategy being added to a graph traversal (use of concrete classes remains viable and is recommended for "native"
-TinkerPop strategies). To use strategies without a concrete class, `TraversalStrategyProxy` can be used in Java, and
-`TraversalStrategy` in Python.
-
-All the following examples will produce the script `g.withStrategies(new MyStrategy(config1:'my value',config2:123))`:
-
-[source,java]
-----
-Map<String, Object> configMap = new LinkedHashMap<>();
- configMap.put("config1", "my value");
- configMap.put("config2", 123);
- TraversalStrategy strategyProxy = new TraversalStrategyProxy("MyStrategy", new MapConfiguration(configMap));
-
- GraphTraversal traversal = g.withStrategies(strategyProxy);
-----
-
-[source,python]
-----
-g.with_strategies(TraversalStrategy(
- strategy_name='MyStrategy',
- config1='my value',
- config2=123
- ))
-----
-
-==== Serialization
-
-The GLVs will only support GraphBinaryV4 and GraphSON support will be removed. This means that the serializer option
-that was available in most GLVs has been removed. GraphBinary is a more compact format and has support for the same
-types. This should lead to increased performance for users upgrading from any version of GraphSON to GraphBinary.
-
-The number of serializable types has been reduced in V4. For example, only a single temporal type remains. You have two
-options when trying to work with data types whose serializer has been removed: first, you can attempt to convert the
-data to another type that still have a serializer or, second, the type may have been too specific and therefore removed
-in which case your provider should have a Provider Defined Type (PDT) for it. See the next paragraph for information on
-PDTs.
-
-Custom serializers have also been removed so if you previously included those as part of your application, they should
-now be removed. In its place, PDTs have been introduced. In particular, there is the Primitive PDT and the Composite
-PDT. Primitive PDTs are string-based representations of a primitive type supported by your provider. Composite types
-contain a map of fields. You should consult your provider's documentation to determine what types of fields a
-particular PDT may contain.
-
-==== Authentication and Authorization
-
-With the move to HTTP, the only authentication option supported out-of-the-box is HTTP basic access authentication
-(username/password). The SASL-based authentication mechanisms are no longer supported (e.g. Kerberos). Your graph
-system provider may choose to implement other authentication mechanisms over HTTP which you would have to use via a
-request interceptor. Refer to your provider's documentation to determine if other authentication mechanisms are
-available.
-
-==== Transactions Disabled
-
-IMPORTANT: 4.0.0-beta.1 Release - Transactions are currently disabled and use of `tx()` will return an error.
-
-==== Removal of Sessions
-
-Support for sessions has been removed. All requests are now "sessionless" with no shared state across subsequent requests.
-
-==== Result Bulking Changes
-
-Previous versions of the Gremlin Server would attempt to "bulk" the result if bytecode was used in the request. This
-"bulking" increased performance by sending similar results once with a count of occurrences. Starting in 4.0, Gremlin
-Server will bulk based on a newly introduced `bulked` field in the `RequestMessage`. It only applies to GraphBinary and
-`gremlin-lang` requests and other requests won't be bulked. This can be toggled in the language variants by setting a
-boolean value with `enableBulkedResult()` in the `Cluster` settings.
-
-==== Gremlin Java Changes
-
-Connection pooling has been updated to work with HTTP. Previously, connections could only be opened one at a time, but
-this has changed and now many connections can be opened at the same time. This supports bursty workloads where many
-queries may be issued within a short period of time. Connections are no longer closed based on how "busy" they are
-based on the `minInProcessPerConnection` and `minSimultaneousUsagePerConnection`, rather they are closed based on an
-idle timeout called `idleConnectionTimeout`. Because the number of connections can increase much faster and connections
-are closed based on a timeout, the `minConnectionPoolSize` option has been removed and there may be zero connections
-available if the driver has been idle for a while.
-
-The Java driver can currently handle a response that is a maximum of 2^31-1 (`Integer.MAX_VALUE`) bytes in size.
-Queries that return more data will have to be separated into multiple queries that return less data.
-
-==== GValue
-
-Parameterization was first added to gremlin-lang in TinkerPop 3.7.0, however was limited in that variables were
-immediately resolved to literals during the compilation of a gremlin script. This direct resolution of variables limited
-providers ability to detect and optimize recurring query patterns.
-
-With this update, a new class `GValue` is introduced which wraps a parameter name and value. Steps which will benefit
-from parameterization have been given overloads to accept GValues. Users can pass GValue's into their traversals to
-inject parameters.
-
-A `GValue` wraps a parameter name and value, and can be provided as input to parameterizable steps when building a
-`GraphTraversal`. The following examples will produce a gremlin script of `g.V().hasLabel(label)` with a parameter map
-of `["label": "person"]`:
-
-[source,java]
-----
-g.V().hasLabel(GValue.of("label", "person"));
-----
-
-[source,python]
-----
-g.V().has_label(GValue('label', 'person'))
-----
-
-Use of `GValue` in traversals with repeated patterns may lead to improved performance in certain graphs. Consult the
-documentation for your specific graph provider for recommendations on how to best utilize `GValue` in traversals.
-
-A new `DefaultVariableResolver` has also been introduced with this change. The grammar will now resolve variables into
-`GValue` which are passed to the constructed traversal, instead of directly resolving them to literals. The old variable
-resolution behavior can still be obtained via the `DirectVariableResolver` if desired.
-
-==== Gremlin Server Default Language
-
-`gremlin-lang` is now the default language and script engine in Gremlin-Server, replacing `gremlin-groovy`. Users may
-still explicitly set the `language` field of a request message to `"gremlin-groovy"` in cases where groovy scripts are
-required.
-
-=== Upgrading for Providers
-
-==== Renaming NoneStep to DiscardStep
-NoneStep, which was primarily used by `iterate()` to discard traversal results in remote contexts, has been renamed to
-DiscardStep. In its place is a new list filtering NoneStep, which takes a predicate as an argument and passes lists with
-no elements matching the predicate.
-
-==== Changes to Serialization
-
-The V4 versions of GraphBinary and GraphSON are being introduced. Support for the older versions of GraphBinary (V1)
-and GraphSON (V1-3) is removed. Upon the full release of 4.0, the GLVs will only use GraphBinary, however, the Gremlin
-Server will support both GraphSON and GraphBinary. The following is a list of the major changes to the GraphBinary
-format:
-
-* Removed type serializers:
-** Period
-** Date
-** TimeStamp
-** Instant
-** ZonedDateTime
-** OffsetTime
-** LocalDateTime
-** LocalDate
-** LocalTime
-** MonthDay
-** YearMonth
-** Year
-** ZoneOffset
-** BulkSet
-** Class
-** Binding
-** Bytecode
-** Barrier
-** Cardinality
-** Column
-** Operator
-** Order
-** Pick
-** Pop
-** Scope
-** DT
-** Lambda
-** P
-** Traverser
-** TextP
-** TraversalStrategy
-** Metrics
-** TraversalMetrics
-** InetAddress
-* OffsetDatetime has been renamed to Datetime. This type maps to `OffsetDateTime` in Java and a `datetime` in Python.
-* Byte is redefined from being unsigned byte to a signed byte.
-* List has a `0x02` value_flag used to denote bulking.
-* Map has a `0x02` value_flag used to denote ordering.
-* `Element` (Vertex, Edge, VertexProperty) labels have been changed from `String` to `List` of `String`.
-* `Element` (Vertex, Edge, VertexProperty) properties are no longer null and are `List` of `Property`.
-* Custom is replaced with Provider Defined Types
-
-One of the biggest differences is in datetime support. Previously, in the Java implementation, `java.util.Date`,
-`java.sql.Timestamp` and most types from the `java.time` package had serializers. This isn't the case in GraphSON 4
-as only `java.time.OffsetDateTime` is supported. Java provides methods to convert amongst these classes so they should
-be used to convert your data to and from `java.time.OffsetDateTime`.
-
-The `GraphSONSerializerProvider` is not used in GraphSON 4. The `GraphSONSerializerProvider` uses the
-`ToStringSerializer` for any unknown type and was used in previous GraphSON versions. Because GraphSON 4 is only
-intended to serialize specific types and not used as a general serializer, GraphSON 4 serializers will throw an error
-when encountering unknown types.
-
-==== Graph System Providers
-
-===== AbstractAuthenticatorHandler Constructor
-
-The deprecated one-arg constructor for `AbstractAuthenticationHandler` has been removed along with two-arg constructors
-for the implementations. Gremlin Server formerly supported the two-arg `Authenticator`, and `Settings` constructor for
-instantiating new custom instances. It now expects implementations of `AbstractAuthenticationHandler` to use a
-three-arg constructor that takes `Authenticator`, `Authorizer`, and `Settings`.
-
-===== GraphManager Changes
-
-The `beforeQueryStart()`, `onQueryError()`, and `onQuerySuccess()` of `GraphManager` have been removed. These were
-originally intended to give providers more insight into when execution occurs in the server and the outcome of that
-execution. However, they depended on `RequestMessage` containing a Request ID, which isn't the case anymore.
-
-===== Gremlin Server Updates
-
-The `OpProcessor` extension point of the server has been removed. In order to extend the functionality of the Gremlin
-Server, you have to implement your own `Channelizer`.
-
-If you are a provider that makes use of the Gremlin Server, you may need to update server configuration YAML files that
-you provide to your users. With the change from WebSockets to HTTP, some of the previous default values are invalid and
-some of the fields no longer exist. See link:https://tinkerpop.apache.org/docs/4.0.0/reference/#_configuring_2[options]
-for an updated list. One of the most important changes is to the `Channelizer` configuration as only the
-`HttpChannelizer` remains and the rest have been removed.
-
-===== Gremlin Server Default Language
-
-`gremlin-lang` is now the default language and script engine in Gremlin-Server, replacing `gremlin-groovy`. Users may
-still explicitly set the `language` field of a request message to `"gremlin-groovy"` in cases where groovy scripts are
-required.
-
-==== Graph Driver Providers
-
-===== Application Layer Protocol Support
-
-HTTP/1.1 is now the only supported application-layer protocol and WebSockets support is dropped. Please follow the
-instructions in the
-link:https://tinkerpop.apache.org/docs/4.0.0/dev/provider/#_graph_driver_provider_requirements[provider documentation]
-for more detailed information. The subprotocol remains fairly similar but has been adjusted to work better with HTTP.
-Also, the move to HTTP means that SASL has been removed as an authentication mechanism and only HTTP basic remains.
-
-===== Request Interceptor
-
-It is strongly recommended that every graph driver provider give a way for users to intercept and modify the HTTP
-request before it is sent off to the server. This capability is needed in cases where the graph system provider has
-additional functionality that can be enabled by modifying the HTTP request.
+1:////
+2:Licensed to the Apache Software Foundation (ASF) under one
+3:or more contributor license agreements. See the NOTICE file
+4:distributed with this work for additional information
+5:regarding copyright ownership. The ASF licenses this file
+6:to you under the Apache License, Version 2.0 (the
+7:"License"); you may not use this file except in compliance
+8:with the License. You may obtain a copy of the License at
+9:
+10: http://www.apache.org/licenses/LICENSE-2.0
+11:
+12:Unless required by applicable law or agreed to in writing,
+13:software distributed under the License is distributed on an
+14:"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+15:KIND, either express or implied. See the License for the
+16:specific language governing permissions and limitations
+17:under the License.
+18:////
+19:
+20:= TinkerPop 4.0.0
+21:
+22:image::gremlins-wildest-dreams.png[width=185]
+23:
+24:*Gremlin's Wildest Dreams*
+25:
+26:== TinkerPop 4.0.0
+27:
+28:*Release Date: NOT OFFICIALLY RELEASED YET*
+29:
+30:Please see the link:https://github.com/apache/tinkerpop/blob/4.0.0/CHANGELOG.asciidoc#release-4-0-0[changelog] for a
+31:complete list of all the modifications that are part of this release.
+32:
+33:=== Upgrading for Users
+34:
+36:===== Declarative Pattern Matching
+37:
+38:Gremlin has always offered both imperative and declarative styles to writing graph queries. While the imperative style
+39:has largely dominated examples and usages, the `match` step has always provided a declarative way to express queries.
+40:The syntax for `match` looked something like this:
+41:
+42:[source,text]
+43:----
+44:gremlin> g.V().match(__.as("a").hasLabel("person").out("created").hasLabel("software").as("s"),
+45:......1> __.as("s").hasLabel("software").in("created").hasLabel("person").as("b")).
+46:......2> where("a", neq("b")).
+47:......3> select("a", "b", "s").by("name")
+48:==>[a:marko,b:josh,s:lop]
+49:==>[a:marko,b:peter,s:lop]
+50:==>[a:josh,b:marko,s:lop]
+51:==>[a:josh,b:peter,s:lop]
+52:==>[a:peter,b:marko,s:lop]
+53:==>[a:peter,b:josh,s:lop]
+54:----
+55:
+56:While this approach worked, it was syntactically complex and since `match` took an arbitrary `Traversal` as arguments,
+57:the declarative style wasn't necessarily enforced well. Moreover, providers found it complicated to optimize `match` as
+58:a step, which meant that, more often than not, it was more performant to simply write the imperative form of the query,
+59:which could take advantage of normal optimization patterns. As a result, `match` never really gained a main stream sort
+60:of usage beyond some fairly narrow use cases.
+61:
+62:In TinkerPop 4.0.0, `match` has a new direction. Instead of taking Gremlin traversals to define the match pattern, it
+63:takes a query string that could technically be any declarative graph query language. Using
+64:link:https://www.iso.org/standard/76120.html[GQL] as an example, the previous Gremlin query using the old `match` style
+65:would look like this:
+66:
+67:[source,text]
+68:----
+69:gremlin> g.match("MATCH (a:person)-[:created]->(s:software), (b:person)-[:created]->(s)").
+70:......1> where("a", neq("b")).
+71:......2> select("a", "b", "s").by("name")
+72:==>[a:marko,b:josh,s:lop]
+73:==>[a:marko,b:peter,s:lop]
+74:==>[a:josh,b:marko,s:lop]
+75:==>[a:josh,b:peter,s:lop]
+76:==>[a:peter,b:marko,s:lop]
+77:==>[a:peter,b:josh,s:lop]
+78:----
+79:
+80:With `match` redesigned in this way users have the opportunity to take advantage of the strengths of declarative query
+81:languages, where it makes sense, while equally retaining the power and feel that Gremlin has always had. The promise of
+82:Gremlin being both imperative and declarative offers a much more compelling story with this model.
+83:
+84:NOTE: The traversal-based form of `match` (e.g. `g.V().match(as("a").out().as("b"))`) is deprecated as of
+85:TinkerPop 4.0.0 and will be removed in a future release. Users should migrate to the new `match(String)` API.
+86:
+87:TinkerPop ships a reference GQL engine for `match()` via the optional `gql-gremlin` module. The engine implements the
+88:link:https://tinkerpop.apache.org/docs/x.y.z/reference/#tinkergql[TinkerGQL] dialect — a deliberate minimal subset of
+89:ISO GQL `MATCH` syntax — and works against any `Graph` implementation through a thin set of default interface methods.
+90:TinkerGraph uses it out of the box with no configuration required. Graph providers that want to offer TinkerGQL support
+91:can add the `gql-gremlin` dependency and register `GqlDeclarativeMatchStrategy` as described in the
+92:link:https://tinkerpop.apache.org/docs/x.y.z/dev/provider/#tinkerpop-providers-tinkergql[provider documentation].
+93:
+94:==== Request Interceptors
+95:
+96:When TinkerPop supported WebSockets prior to 4.0.0, the Java driver offered a `RequestInterceptor` interface (and
+97:its predecessor, `HandshakeInterceptor`) that allowed modification of the raw Netty `FullHttpRequest`. For WebSocket
+98:connections, the interceptor only ran on the initial HTTP upgrade handshake. With the move to HTTP, the notion of
+99:the "interceptor" has shifted to a per-request concern that is now standardized across all GLVs.
+100:
+101:All GLVs now support request interceptors, which allow modification of the HTTP request before it is sent to the
+102:server. An interceptor is a function that receives the mutable HTTP request object and can modify headers, the
+103:request body, the URI, or the HTTP method. Interceptors are run in the order they are registered.
+104:
+105:The most common use case for interceptors is authentication (e.g., SigV4 signing), but they can also be used to add
+106:provider-specific fields, inject custom headers, or transform the request body.
+107:
+108:Here is a simple Java example that adds a custom header:
+109:
+110:[source,java]
+111:----
+112:Cluster cluster = Cluster.build("localhost")
+113: .interceptors(request -> request.headers().put("X-Custom-Header", "value"))
+114: .create();
+115:----
+116:
+117:Authentication is also an interceptor. Each GLV provides convenience methods (e.g., `Auth.basic()`, `Auth.sigv4()`)
+118:that return interceptors and can be registered alongside custom ones.
+119:
+120:For full details on the interceptor API for each language variant, refer to the RequestInterceptor section in
+121:each GLV's documentation in the
+122:link:https://tinkerpop.apache.org/docs/x.y.z/reference/#gremlin-drivers-variants[Gremlin Drivers and Variants]
+123:reference.
+125:==== Multi-Label Support
+126:
+127:Until now, vertices in the property graph model were limited to a single, immutable label assigned at creation. This
+128:release introduces configurable label cardinality, allowing vertices to carry multiple labels that can be added and
+129:removed over their lifetime.
+130:
+131:The feature is controlled by `LabelCardinality`, a graph-level setting that defaults to `ONE`, preserving the
+132:existing single-label behavior. To enable multi-label in TinkerGraph, set the vertex label cardinality in the graph
+133:properties:
+134:
+135:```
+136:gremlin.tinkergraph.vertexLabelCardinality=ZERO_OR_MORE
+137:```
+138:
+139:The three modes are `ONE` (single, immutable, the 3.x default), `ONE_OR_MORE` (mutable, minimum one), and
+140:`ZERO_OR_MORE` (fully flexible). Edge labels remain fixed at `ONE`.
+141:
+142:With multi-label enabled, several new traversal steps become available:
+143:
+144:```text
+145:gremlin> g.addV('person','employee').property('name','marko')
+146:==>v[0]
+147:gremlin> g.V().has('name','marko').addLabel('manager')
+148:==>v[0]
+149:gremlin> g.V().has('name','marko').labels()
+150:==>person
+151:==>employee
+152:==>manager
+153:gremlin> g.V().has('name','marko').dropLabel('employee').labels()
+154:==>person
+155:==>manager
+156:```
+157:
+158:The `labels()` step is a flatMap that emits one traverser per label, unlike `label()` which returns a single string.
+159:For single-label vertices the two behave identically.
+160:
+161:The `mergeV()` step accepts a list for `T.label` to match or create multi-label vertices. The `onMatch` option uses
+162:append-only semantics: new labels are added, existing labels are preserved:
+163:
+164:```text
+165:gremlin> g.mergeV([(T.label): ['person','employee'], name: 'marko'])
+166:==>v[0]
+167:gremlin> g.mergeV([(T.label): 'person', name: 'marko']).option(Merge.onMatch, [(T.label): 'director'])
+168:==>v[0]
+169:```
+170:
+171:By default, `elementMap()` and `valueMap()` continue to return labels as a single string. To receive all labels as a
+172:set, use `with("multilabel")` either per-traversal or as a persistent source configuration:
+173:
+174:```text
+175:// assuming a vertex with labels [person, employee, manager] and name "marko"
+176:gremlin> g.with("multilabel").V().has('name','marko').elementMap()
+177:==>{id=0, label=[manager, person, employee], name=marko}
+178:gremlin> g.V().has('name','marko').elementMap()
+179:==>{id=0, label=manager, name=marko}
+180:```
+181:
+182:To avoid repeating `with("multilabel")` on every traversal, create a persistent source:
+183:
+184:```text
+185:gremlin> gml = g.with("multilabel")
+186:==>graphtraversalsource[tinkergraph[vertices:1 edges:0], standard]
+187:gremlin> gml.V().has('name','marko').elementMap()
+188:==>{id=0, label=[manager, person, employee], name=marko}
+189:gremlin> gml.V().has('name','marko').valueMap(true)
+190:==>{id=0, label=[manager, person, employee], name=[marko]}
+191:```
+192:
+193:Note the following behavioral details:
+194:
+195:* The deprecated `label()` step returns a single, non-deterministic label when multiple labels are present. Always
+196: use `labels()` to retrieve the full set reliably.
+197:* Serialization via GraphSON V1/V2/V3 or Gryo only transmits one label per vertex (using `label()`). Multi-label data
+198: will be silently reduced to a single label when passing through these older formats. Only GraphBinary (V4) and
+199: GraphSON V4 preserve the full label set.
+200:* Adding a label that already exists on the vertex is a no-op (when multi-label is enabled). Dropping a label that
+201: does not exist is also a no-op. With cardinality `ONE`, both `addLabel()` and `dropLabel()` throw since labels are
+202: immutable.
+204:
+205:==== Gremlator
+206:
+207:link:https://gremlator.com[Gremlator] has been rebuilt entirely in JavaScript as a browser-based single-page
+208:application and is now an official part of the Apache TinkerPop project. It translates Gremlin queries into
+209:equivalent representations in all supported language variants: Groovy, Java, Python, JavaScript, Go, .NET, and an
+210:anonymized form. The original gremlator.com was a prototype built by TinkerPop committer Dave Bechberger; the
+211:previous implementation required Java and a running Gremlin Server, whereas the new version runs entirely in the
+212:browser with no server infrastructure needed.
+213:
+214:==== GLV Transaction Support
+215:
+216:All non-Java Gremlin Language Variants (gremlin-python, gremlin-go, gremlin-javascript, gremlin-dotnet) now support
+217:explicit remote transactions over HTTP. The transaction model is the same across all GLVs: begin a transaction, submit
+218:traversals within it, then commit or rollback. Data is isolated until committed.
+219:
+220:Each GLV provides two entry points:
+221:
+222:* **Traversal API**: `g.tx().begin()` returns a transaction-bound `GraphTraversalSource`
+223:* **Driver API**: `client.transact()` (or `client.Transact()` in .NET) returns a `Transaction` with `submit()` methods
+224:
+225:Key behaviors consistent across all GLVs:
+226:
+227:* Transactions are not thread-safe. All operations must be sequential.
+228:* The default close behavior is rollback (partial work discarded if commit is not called explicitly).
+229:* Transactions are single-use. After commit or rollback, a new transaction must be created.
+230:* `gtx.tx()` returns the same transaction object (enabling `gtx.tx().commit()` pattern from the Traversal API).
+231:
+232:See the <<gremlin-drivers-variants,Gremlin Drivers and Variants>> reference documentation for language-specific
+233:syntax and examples.
+234:
+235:==== Transaction Default Close Behavior Changed
+236:
+237:The default behavior of `close()` on a remote transaction has been changed from `commit` to `rollback` across all
+238:GLVs (including the Java driver). This aligns with the embedded graph transaction default and is the safer behavior:
+239:partial work is discarded if the user forgets to call `commit()`. In Java (both remote and embedded mode), the behavior
+240:can still be overridden via `tx.onClose(Transaction.CLOSE_BEHAVIOR.COMMIT)`. The non-Java GLVs do not support
+241:configuring close behavior and always rollback.
+242:
+243:==== Removed `uuid` Dependency in gremlin-javascript
+244:
+245:The `uuid` npm package has been removed from `gremlin-javascript`. UUID generation now uses the built-in
+246:`globalThis.crypto.randomUUID()` API, which is available in Node.js 19+ and all modern browsers.
+247:
+248:This change has no impact on how UUID values are sent to or received from the server — UUID serialization and
+249:deserialization in GraphBinary is unchanged. Applications that depend on the `uuid` package solely because
+250:`gremlin-javascript` brought it in as a transitive dependency should add it directly to their own `package.json`
+251:if they still need it.
+252:
+253:==== JS HTTP Streaming Response Support
+254:
+255:The JavaScript driver now supports incremental HTTP streaming. Results are deserialized from the server response as
+256:they arrive, rather than buffering the entire response before processing.
+257:
+258:Traversal API terminal steps (`next()`, `toList()`, `hasNext()`) are now truly incremental. `next()`
+259:returns the first result as soon as it is deserialized from the wire, without waiting for the full response.
+260:In 3.x, `next()` waited for all WebSocket frames before returning.
+261:
+262:`Client.stream()` now returns an `AsyncGenerator` for direct incremental consumption. This is a breaking change
+263:from 3.x where `stream()` returned a Node.js `Readable`. The new return type works in both Node.js and browsers:
+264:
+265:[source,javascript]
+266:----
+267:// 3.x — Readable stream (no longer supported)
+268:// const stream = client.stream('g.V()');
+269:// stream.on('data', (resultSet) => { ... });
+270:
+271:// 4.0 — AsyncGenerator
+272:for await (const item of client.stream('g.V()', null)) {
+273: console.log(item);
+274: if (someCondition) break; // stops reading from the HTTP stream
+275:}
+276:----
+277:
+278:`Client.submit()` remains unchanged. It still buffers the full response and returns `Promise<ResultSet>`.
+279:
+280:==== New Gremlin-Lang Literals
+281:
+282:The canonical Gremlin grammar now includes literal syntax for `Character`, `Duration`, and `Binary` types. These
+283:literals can be used directly in traversals without falling back to parameter serialization.
+284:
+285:===== Character
+286:
+287:A character literal is a single-character string with a `c` suffix:
+288:
+289:[source,text]
+290:----
+291:g.V().has("initial","M"c)
+292:----
+293:
+294:NOTE: Character is not supported in gremlin-go or gremlin-javascript.
+295:
+296:===== Duration
+297:
+298:A duration literal uses seconds and nanoseconds with an optional sign flag:
+299:
+300:[source,text]
+301:----
+302:Duration(seconds,nanos)
+303:Duration(seconds,nanos,false)
+304:----
+305:
+306:The first argument is seconds (non-negative integer), the second is nanoseconds (integer, 0 to 999999999). The
+307:optional third argument is an `isPositive` boolean that defaults to `true` when omitted. Set it to `false` for
+308:negative durations.
+309:
+310:[source,text]
+311:----
+312:g.V().has("length",P.gt(Duration(3600,0)))
+313:----
+314:
+315:NOTE: Python's `timedelta` has microsecond resolution, so sub-microsecond nanosecond values are truncated.
+316:.NET's `TimeSpan` has 100-nanosecond tick resolution, so sub-100ns values are truncated.
+317:
+318:NOTE: Duration is not supported in gremlin-javascript.
+319:
+320:===== Binary
+321:
+322:A binary literal wraps a base64-encoded string:
+323:
+324:[source,text]
+325:----
+326:Binary("AQID")
+327:Binary("")
+328:----
+329:
+330:Each GLV maps this to its native byte array type:
+331:
+332:[source,text]
+333:----
+334:g.V().has("blob",P.eq(Binary("AQID")))
+335:----
+336:
+337:See: link:https://issues.apache.org/jira/browse/TINKERPOP-3153[TINKERPOP-3153]
+338:
+339:==== Python HTTP Streaming Response Support
+340:
+341:The Python driver now streams results directly from the HTTP response body through the configured
+342:`response_serializer`. Results are available to the caller as they arrive from the server, rather than waiting for
+343:the full response to be buffered in memory. This improves memory efficiency for large result sets and reduces
+344:time-to-first-result.
+345:
+346:Traversal API terminal steps (`next()`, `to_list()`, `has_next()`) are now truly incremental. `next()` returns the
+347:first result as soon as it is deserialized from the wire, without waiting for the full response. In 3.x, `next()`
+348:waited for all data to be buffered before returning.
+349:
+350:The following internal APIs have changed:
+351:
+352:- `max_content_length` is no longer supported. Response size limits should be configured server-side via
+353: `maxRequestContentLength`.
+354:- The built-in response serializer is `GraphBinarySerializersV4`. The receive path dispatches through the
+355: configured `response_serializer`.
+356:- `ResultSet` now yields individual items instead of lists when iterated. Code that uses `results += result`
+357: to accumulate results from a `ResultSet` iterator must change to `results.append(result)`. The `to_list()`
+358: and `all()` APIs are unaffected and remain the recommended way to collect results.
+359:
+360:==== Python Driver Simplification — Removed GraphSON, Abstract Base Classes, and Protocol Layer
+361:
+362:The `AbstractBaseTransport`, `AbstractBaseProtocol`, and `GremlinServerHTTPProtocol` classes have been removed from
+363:`gremlin-python`. The protocol layer's request-building logic (serialization, headers, interceptors, auth) has been
+364:merged directly into `Connection`. The driver now uses `AiohttpHTTPTransport` directly without an abstract transport
+365:interface.
+366:
+367:`GremlinServerError` has moved from `gremlin_python.driver.protocol` to `gremlin_python.driver.connection`:
+368:
+369:The `GraphSONSerializersV4` class and the `gremlin_python.structure.io.graphsonV4` module have been removed.
+370:GraphBinary is the only supported wire format for the Python driver in TinkerPop 4. Code that constructed
+371:`GraphSONSerializersV4()` or imported from `gremlin_python.structure.io.graphsonV4` must switch to
+372:`GraphBinarySerializersV4` (the default `request_serializer` and `response_serializer`):
+373:
+374:[source,python]
+375:----
+376:# Before
+377:from gremlin_python.driver.protocol import GremlinServerError
+378:
+379:# After
+380:from gremlin_python.driver.connection import GremlinServerError
+381:----
+382:
+383:The `protocol_factory` and `transport_factory` parameters have been removed from `Client`,
+384:`DriverRemoteConnection`, and `Connection`. Users who were passing a custom `protocol_factory` should use the
+385:`request_serializer`, `response_serializer`, `auth`, and `interceptors` parameters directly instead — these cover
+386:all functionality that `GremlinServerHTTPProtocol` previously provided.
+387:
+388:Transport options like SSL and timeouts are now passed as keyword arguments directly:
+389:
+390:[source,python]
+391:----
+392:# Before
+393:from gremlin_python.driver.aiohttp.transport import AiohttpHTTPTransport
+394:Client(url, 'g', transport_factory=lambda: AiohttpHTTPTransport(ssl_options=ctx, read_timeout=30))
+395:
+396:# After
+397:Client(url, 'g', ssl_options=ctx, read_timeout=30)
+398:----
+399:
+400:The `Connection` constructor signature has changed. The `protocol` and `transport_factory` positional arguments have
+401:been removed. Transport kwargs are forwarded to `AiohttpHTTPTransport` internally:
+402:
+403:[source,python]
+404:----
+405:# Before
+406:Connection(url, traversal_source, protocol, transport_factory, executor, pool)
+407:
+408:# After
+409:Connection(url, traversal_source, executor, pool,
+410: request_serializer=None, response_serializer=None,
+411: auth=None, interceptors=None, **transport_kwargs)
+412:----
+413:
+414:Custom transport implementations are no longer supported. The driver uses `AiohttpHTTPTransport` directly.
+415:
+416:==== Removal of sparql-gremlin
+417:
+418:The `sparql-gremlin` module has been removed following a prolonged period of inactivity. There is currently no direct
+419:replacement planned for this functionality.
+420:
+421:See: link:https://issues.apache.org/jira/browse/TINKERPOP-3249[TINKERPOP-3249]
+422:
+423:==== Runtime Upgrades
+424:
+425:The minimum target framework is now `net8.0` (previously `netstandard2.0;net6.0`). .NET 6 reached end-of-life in
+426:November 2024; .NET 8 is the current LTS release.
+427:
+428:==== .NET HTTP Streaming Response Support
+429:
+430:The .NET driver (`Gremlin.Net`) now uses streaming deserialization, results are deserialized incrementally from the
+431:HTTP response stream as bytes arrive over the network, rather than buffering the entire response before processing.
+432:This reduces memory usage and latency for large result sets.
+433:
+434:The traversal API (`Next()`, `ToList()`, `HasNext()`, `ToSet()`, `Iterate()`) is unchanged — these methods block
+435:internally on the async stream, so existing traversal code works without modification.
+436:
+437:`ResultSet<T>` no longer implements `IReadOnlyCollection<T>`. It now implements `IAsyncEnumerable<T>`, backed by a
+438:`Channel<T>` that receives items from a background deserialization task. Users who access `ResultSet<T>` directly
+439:via `GremlinClient.SubmitAsync<T>()` will need to update their code:
+440:
+441:[source,csharp]
+442:----
+443:// 3.x — ResultSet was IReadOnlyCollection<T>
+444:var resultSet = await client.SubmitAsync<int>("g.inject(1,2,3)");
+445:var count = resultSet.Count; // no longer available
+446:foreach (var item in resultSet) { } // no longer available
+447:
+448:// 4.0 — ResultSet is IAsyncEnumerable<T>
+449:var resultSet = await client.SubmitAsync<int>("g.inject(1,2,3)");
+450:var list = await resultSet.ToListAsync(); // materialize if you need Count
+451:await foreach (var item in resultSet) { } // async iteration
+452:----
+453:
+454:The `IMessageSerializer` interface has also changed: `DeserializeMessageAsync` now accepts a `Stream` and returns
+455:`IAsyncEnumerable<object>` instead of accepting `byte[]` and returning `Task<ResponseMessage<List<object>>>`.
+456:Custom serializer implementations will need to be updated. The `ResponseMessage<T>` type has been removed.
+457:
+458:With streaming, server errors (`ResponseException`) are now thrown during result iteration rather than during
+459:`SubmitAsync`. Code that catches `ResponseException` around `SubmitAsync` should be updated to catch around the
+460:result consumption instead:
+461:
+462:[source,csharp]
+463:----
+464:// 3.x — exception thrown during SubmitAsync
+465:try {
+466: var resultSet = await client.SubmitAsync<int>("invalid");
+467:} catch (ResponseException ex) { ... }
+468:
+469:// 4.0 — exception thrown during iteration
+470:var resultSet = await client.SubmitAsync<int>("invalid");
+471:try {
+472: var list = await resultSet.ToListAsync();
+473:} catch (ResponseException ex) { ... }
+474:----
+475:
+476:The traversal API is not affected — `Next()`, `ToList()`, etc. still throw `ResponseException` directly since they
+477:block on the async stream internally.
+478:
+479:==== Streaming Response Deserialization in gremlin-driver
+480:
+481:The Java driver now deserializes HTTP responses incrementally, delivering results to the `ResultSet` as they arrive
+482:rather than buffering the entire response. This reduces time-to-first-result for large result sets.
+483:
+484:This change is automatic and requires no code changes. It applies only when using the default GraphBinary serializer.
+485:Custom `MessageSerializer` implementations fall back to the non-streaming pipeline that buffers the full response
+486:before deserialization. The `ResultSet` API is unchanged.
+487:
+488:==== More Secure Gremlin Server
+489:
+490:Previous versions of Gremlin Server relied on a Gremlin-flavored Groovy `ScriptEngine` for basic server initialization,
+491:which covered binding traversal sources, loading data, and running lifecycle hooks all set up by Groovy initialization
+492:scripts. This meant the Groovy `ScriptEngine` was active by default, even for users who only needed to send standard
+493:Gremlin queries.
+494:
+495:TinkerPop 4.0 addresses this in two ways. First, `gremlin-lang` replaces `gremlin-groovy` as the default `ScriptEngine`
+496:for remote script execution, so standard Gremlin queries no longer require a general-purpose scripting engine. Second,
+497:server initialization is now handled through declarative YAML configuration, removing the last reason Groovy needed to
+498:be active by default.
+499:
+500:As of this release, Groovy is completely disabled by default throughout the entire server lifecycle. Users who
+501:explicitly need Groovy script execution can still opt in, but it is no longer required for any standard usage. A future
+502:release may remove Groovy as an installed option in the server distribution altogether.
+503:
+504:===== Simplified Server Configuration
+505:
+506:The most basic server setup, initializing a basic graph with a traversal source, previously required a Groovy init
+507:script just to create the `g` binding. Now, any graph defined in the `graphs` section automatically gets a
+508:`TraversalSource` according to these rules:
+509:
+510:* A graph named `graph` is implicitly bound to `g`
+511:* All others are bound to `g_<graph-name>` (e.g. `modern` gets `g_modern`)
+512:
+513:A fully functional minimal configuration is now simply:
+514:
+515:[source,yaml]
+516:----
+517:graphs: {
+518: graph: conf/tinkergraph-empty.properties}
+519:----
+520:
+521:===== Strategy Configuration via `traversalSources`
+522:
+523:For cases that require custom traversalSource naming or strategies on a `TraversalSource` (e.g. `ReadOnlyStrategy`), the
+524:`traversalSources` list within a graph entry provides explicit control without scripting:
+525:
+526:[source,yaml]
+527:----
+528:graphs: {
+529: graph: {
+530: configuration: conf/tinkergraph-empty.properties,
+531: traversalSources: [
+532: {name: g},
+533: {name: gReadOnly, gremlinExpression: "g.withStrategies(ReadOnlyStrategy)"}]}}
+534:----
+535:
+536:Each entry specifies:
+537:
+538:- `name` (required): the binding name for the `TraversalSource`
+539:- `gremlinExpression` (optional): a Gremlin expression evaluated with a base traversal source bound as `g`
+540:- `language` (optional): which `ScriptEngine` to use for the expression (defaults to `gremlin-lang`, or the sole
+541:configured engine if only one is present)
+542:
+543:Graphs with explicit `traversalSources` entries are excluded from the implicitly defined traversal sources described in
+544:the previous section.
+545:
+546:===== Java-Based Lifecycle Hooks
+547:
+548:For startup and shutdown logic that goes beyond declarative configuration such as loading sample data, initializing
+549:caches, or custom setup, Java-based `LifeCycleHook` implementations can now replace Groovy init scripts:
+550:
+551:[source,yaml]
+552:----
+553:lifecycleHooks:
+554: - className: org.apache.tinkerpop.gremlin.server.util.TinkerFactoryDataLoader
+555: config: {graph: graph, dataset: modern}
+556:----
+557:
+558:Each entry specifies a `className` implementing `LifeCycleHook` and an optional `config` map passed to the hook's
+559:`init()` method. The built-in `TinkerFactoryDataLoader` supports datasets: `airroutes`, `modern`, `classic`, `crew`,
+560:`grateful`, and `sink`.
+561:
+562:===== Migrating from Groovy Init Scripts
+563:
+564:Creating `TraversalSource` and `LifeCycleHook` instances via Groovy init scripts is now deprecated. Existing scripts
+565:continue to work when `GremlinGroovyScriptEngine` is explicitly configured, but a deprecation warning is logged at
+566:startup. Support for Groovy script initialization and customization may be dropped in a future release.
+567:
+568:*Before (Groovy init script):*
+569:
+570:[source,groovy]
+571:----
+572:def globals = [:]
+573:globals << [hook : [
+574: onStartUp: { ctx ->
+575: org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerFactory.generateModern(graph)
+576: }
+577:] as LifeCycleHook]
+578:globals << [g : traversal().withEmbedded(graph)]
+579:----
+580:
+581:*After (YAML only):*
+582:
+583:[source,yaml]
+584:----
+585:graphs: {
+586: graph: conf/tinkergraph-empty.properties}
+587:lifecycleHooks:
+588: - { className: org.apache.tinkerpop.gremlin.server.util.TinkerFactoryDataLoader, config: {graph: graph, dataset: modern}}
+589:----
+590:
+591:The `g` binding is implicitly created from the `graph` entry. No `scriptEngines` section is needed.
+592:
+593:===== `ScriptEngine` Allowlist
+594:
+595:The `scriptEngines` configuration in the Gremlin Server YAML now acts as an allowlist. Only `ScriptEngine`
+596:implementations explicitly listed in the configuration will accept requests. The `gremlin-lang` `ScriptEngine` is always
+597:available regardless of configuration.
+598:
+599:Previously, any `GremlinScriptEngineFactory` discovered via Java's `ServiceLoader` mechanism on the classpath could be
+600:used by clients, even if it was not listed in the server's `scriptEngines` configuration. This meant that
+601:`gremlin-groovy` was always available as long as its JAR was on the classpath, regardless of the server configuration.
+602:
+603:With this change, a request specifying a `language` that is not in the `scriptEngines` configuration will receive a
+604:`400 Bad Request` response. Providers who rely on `gremlin-groovy` or any other `ScriptEngine` must explicitly include
+605:it in their `scriptEngines` configuration:
+606:
+607:[source,yaml]
+608:----
+609:scriptEngines: {
+610: gremlin-lang: {},
+611: gremlin-groovy: {
+612: plugins: {
+613: org.apache.tinkerpop.gremlin.server.jsr223.GremlinServerGremlinPlugin: {}}}}
+614:----
+615:
+616:See: link:https://issues.apache.org/jira/browse/TINKERPOP-2720[TINKERPOP-2720],
+617:link:https://issues.apache.org/jira/browse/TINKERPOP-3107[TINKERPOP-3107]
+618:
+619:==== `gremlin-lang` based Parameters
+620:
+621:Bindings/parameters that are sent as part of the request are now `gremlin-lang` string maps rather than an actual Map
+622:that would have been serialized based on the serializer used for the request. A side effect of this is that the map key
+623:must be a valid Java identifier. This means that certain items can no longer be sent like `#jsr223` control flags that
+624:were used for the `gremlin-groovy` ScriptEngine. Ensure that you are using valid Java identifiers (e.g. start with a
+625:letter, no spaces, can't use reserved keywords, etc.) for keys.
+626:
+627:Since parameters are now text-based gremlin-lang literals, `Traversal` objects can no longer be passed as binding
+628:values. In previous versions it was possible to pass a traversal as a parameter:
+629:
+630:[source,text]
+631:----
+632:// 3.x — no longer supported in 4.0
+633:client.submit("g.V(x)", Map.of("x", __.has("name","marko")));
+634:----
+635:
+636:This pattern is now rejected by the server as a security measure to prevent traversal injection through parameter maps.
+637:Traversals should be composed directly in the Gremlin query string rather than supplied as parameters.
+638:
+639:Parameter maps are also subject to a maximum nesting depth of 32 levels. Deeply nested map or collection structures
+640:beyond this limit will be rejected with an error.
+641:
+642:See: link:https://issues.apache.org/jira/browse/TINKERPOP-3247[TINKERPOP-3247]
+643:
+644:==== JavaScript Typed Numeric Wrappers
+645:
+646:JavaScript has a single `Number` type (IEEE 754 double) which loses the distinction between Gremlin numeric types like
+647:`int`, `float`, `long`, and `double`. The `gremlin-javascript` driver now provides typed wrapper classes and factory
+648:functions that give explicit control over how numbers are serialized and deserialized.
+649:
+650:On the *serialization* side, wrapping a value controls the GremlinLang type suffix and GraphBinary type code sent to
+651:the server:
+652:
+653:[source,javascript]
+654:----
+655:const { toInt, toLong, toFloat, toDouble } = gremlin.structure;
+656:
+657:g.V().has('age', toInt(29)).next(); // age sent as Int
+658:g.V().has('score', toFloat(3.14)).next(); // score sent as Float
+659:g.V().has('id', toLong('9007199254740993')).next(); // id sent as Long
+660:----
+661:
+662:`toLong()` accepts `number`, `string`, or `bigint`. Number inputs must be within the safe integer range (throws
+663:`RangeError` otherwise); string and bigint inputs support the full signed 64-bit range.
+664:
+665:Without wrappers, the driver continues to infer types automatically from the JavaScript value, so existing code is
+666:unaffected.
+667:
+668:On the *deserialization* side, a new `preciseNumbers: true` connection option wraps incoming numeric values in the
+669:same typed wrappers, preserving the server's original type information:
+670:
+671:[source,javascript]
+672:----
+673:const g = traversal().with_(new DriverRemoteConnection('http://localhost:8182/gremlin', {
+674: preciseNumbers: true
+675:}));
+676:
+677:const v = await g.V(1).elementMap().next();
+678:const age = v.value.get('age'); // Int { value: 29, type: 'int' }
+679:age + 1; // 30 — wrappers support arithmetic via valueOf()
+680:----
+681:
+682:The `unwrap()` helper extracts the raw value from any wrapper, passing non-wrapper values through unchanged:
+683:
+684:[source,javascript]
+685:----
+686:const { unwrap } = gremlin.structure;
+687:unwrap(toInt(29)); // 29
+688:unwrap('hello'); // 'hello'
+689:----
+690:
+691:==== Subgraph Support in GLVs
+692:
+693:All GLVs now support the `subgraph()` step. Previously, calling `subgraph()` from a GLV produced an unknown-type error
+694:because the variant could not interpret the `Graph` payload that the server returned. Applications can now extract a
+695:portion of a remote graph as part of a normal traversal and inspect its vertices and edges directly from the client,
+696:without having to re-issue queries to reconstruct the result. See: <<subgraph-step>>.
+697:
+698:In the GLVs, the result is a detached snapshot of the captured vertices and edges, not a traversable `Graph` instance.
+699:It cannot be passed to `traversal().with(...)`, and mutating its collections has no effect on the source graph. To
+700:re-query elements against the original graph, extract their ids and call `g.V(id)` or `g.E(id)` against the original
+701:`GraphTraversalSource`.
+702:
+703:==== Provider Defined Types
+704:
+705:Graph providers may now expose custom types as Provider Defined Types (PDT) (replacing the old `CustomTypeSerializer`
+706:mechanism). The key improvement is that the default case now works out of the box — drivers deserialize PDT values
+707:as `ProviderDefinedType` objects containing a `name` and a `fields` map without any configuration, eliminating
+708:the serializer errors that occurred with unknown custom types in TP3. For automatic conversion between PDT values and
+709:application-specific types, each driver supports an optional registry or annotation mechanism, which requires similar
+710:effort to the old custom serializer approach but is entirely optional for basic usage:
+711:
+712:* <<gremlin-java-pdt,Gremlin-Java>>
+713:* <<gremlin-python-pdt,Gremlin-Python>>
+714:* <<gremlin-javascript-pdt,Gremlin-JavaScript>>
+715:* <<gremlin-dotnet-pdt,Gremlin.Net>>
+716:* <<gremlin-go-pdt,Gremlin-Go>>
+717:
+718:
+719:==== Tree No Longer Extends HashMap
+720:
+721:`Tree` no longer extends `HashMap`. It is now a `final` class that holds a `Map` internally and exposes a
+722:tree-shaped API instead of `Map` methods. This is a breaking change for code that treated a `tree()` result as a
+723:`Map`.
+724:
+725:Replacements for the common `Map`-based access patterns:
+726:
+727:[options="header"]
+728:|=======================
+729:|3.x (`Tree` as `Map`) |4.x (`Tree` API)
+730:|`tree.get(key)` |`tree.childAt(key)` (throws if absent) or `tree.findSubtree(key)` (recursive, returns `Optional`)
+731:|`tree.containsKey(key)` |`tree.hasChild(key)`
+732:|`tree.keySet()` |`tree.rootNodes()`
+733:|`tree.size()` |`tree.rootNodes().size()` for root entries, or `tree.nodeCount()` for total nodes
+734:|`getObjectsAtDepth(d)` |`getNodesAtDepth(d)` (now 0-based: depth 0 returns the roots)
+735:|`getLeafObjects()` |`getLeafNodes()`
+736:|=======================
+737:
+738:A few Gremlin patterns that worked only because `Tree` was a `Map` (for example `select(keys)` and `unfold()`
+739:applied to a `Tree`) no longer compose. Process the `Tree` result client-side after `next()`, or reshape the
+740:upstream traversal.
+741:
+742:`count(local)` on a `Tree` has changed semantics. Previously, because `Tree` was a `Map`, it returned the
+743:number of root entries; it now returns the total number of nodes in the tree (`Tree.nodeCount()`), consistent
+744:with how `count(local)` counts the contents of other local objects (for example the objects in a `Path`). Use
+745:`rootNodes().size()` on the materialized `Tree` if the root-entry count is required.
+746:
+747:`isLeaf()` no longer throws on an empty tree (it returns `true`), and a `Tree` keeps the long-standing limitation
+748:that sibling branches resolving to the same value collapse into one node; use `path()` or `subgraph()` when full
+749:path structure must be preserved.
+750:
+751:See: link:https://lists.apache.org/thread/o0nqh6kmrkdht531655p351ldjll045d[[DISCUSS] Make Tree no longer extend HashMap]
+752:
+753:
+754:=== Upgrading for Providers
+755:
+756:==== Graph System Providers
+757:
+759:===== Provider Defined Types
+760:
+761:TinkerPop 4 replaces the TP3 `CustomTypeSerializer` mechanism with Provider Defined Types (PDT). The TP3 extension
+762:point has been removed entirely and there is no backward-compatible bridge, so any existing `CustomTypeSerializer`
+763:implementations must be migrated: providers expose their custom types by annotating classes with `@ProviderDefined`
+764:or, for types they don't own, by implementing `ProviderDefinedTypeAdapter<T>`. Adapters are discovered automatically
+765:via ServiceLoader, so this requires similar effort to the old approach.
+766:
+767:The key improvement is that driver users now receive PDT values as structured `ProviderDefinedType` objects by
+768:default, without any configuration — eliminating the serializer errors that unknown custom types caused in TP3, and
+769:benefiting all driver users transparently.
+770:
+771:See <<provider-defined-types>> for full details on annotation usage, field filtering, nested types, and ServiceLoader
+772:registration.
+773:
+774:`Tree` no longer extends `HashMap`. Provider code that inspected or rebuilt a `Tree` via `Map` methods
+775:(`get`, `put`, `keySet`, `entrySet`, `size`) must use the tree-shaped API instead: read with `rootNodes()` +
+776:`childAt(key)` and build with `getOrCreateChild(key)` + `addTree(subtree)`. The GraphSON (`g:Tree`) and
+777:GraphBinary (`0x2b`) wire formats are unchanged, so no GraphSON- or GraphBinary-serialized data or cross-version
+778:===== Tree Serialization and API Changes
+779:
+780:`Tree` no longer extends `HashMap`.
+781:
+782:Providers that use the reference (de)serializers receive a `Tree` instance from TinkerPop. Code that inspected or
+783:rebuilt that `Tree` via `Map` methods (`get`, `put`, `keySet`, `entrySet`, `size`) must use the tree-shaped API
+784:instead: read with `rootNodes()` + `childAt(key)` and build with `getOrCreateChild(key)` + `addTree(subtree)`.
+785:
+786:The GraphSON (`g:Tree`) and GraphBinary (`0x2b`) wire formats are unchanged, so no GraphSON- or GraphBinary-serialized data or cross-version
+787:compatibility is affected. The Gryo `Tree` wire format, however, did change: in 3.x a `Tree` was serialized via
+788:Kryo's default `Map` serializer because it extended `HashMap`, whereas in 4.x it has an explicit `Tree`
+789:serializer. As a result, Gryo-serialized `Tree` data written by 3.x cannot be read by 4.x and vice versa. The
+790:Gryo type registration id (`61`) is unchanged and 4.x-to-4.x Gryo round-trips correctly; this Gryo break is
+791:expected for the 4.0.0 major release.
+793:===== Multi-Label Support
+794:
+795:Providers declare their supported label cardinality via `Graph.Features.getLabelCardinality()`, which defaults to
+796:`LabelCardinality.ONE` (single label, immutable, the 3.x behavior). To support multi-label, return `ONE_OR_MORE` or
+797:`ZERO_OR_MORE` from this method.
+798:
+799:The `LabelCardinality` enum exposes `min()`, `max()`, and `supportsMutation()` for programmatic introspection of
+800:constraints. Constraint enforcement is handled by the `LabelCardinalityValidator` utility class, which providers may
+801:use directly or replace with their own validation logic tailored to their storage backend.
+802:
+803:Providers implementing multi-label must:
+804:
+805:- Store and return a `Set<String>` from `Element.labels()`
+806:- Implement `Element.addLabel(String, String...)` and `Element.dropLabel(String, String...)`
+807:- Ensure `hasLabel("a", "b")` uses OR semantics (matches vertices with label "a" or "b")
+808:- Serialize/deserialize the label set via the V4 GraphBinary format (which sends labels as a list)
+809:
+810:Older serialization formats (GraphSON V1/V2/V3, Gryo) only support a single label and will silently use the value
+811:from `Element.label()` (the deprecated single-label accessor).
+813:
+814:==== Graph Driver Providers
+815:
+816:===== Request Interceptors
+817:
+818:Graph driver providers should implement request interceptor support in their drivers. Interceptors allow users to
+819:modify the HTTP request before it is sent, which is essential for authentication schemes (like SigV4), adding
+820:provider-specific request fields, and other server-specific capabilities.
+821:
+822:All TinkerPop reference drivers now include interceptor support. The interceptor contract is standardized across all
+823:GLVs: interceptors receive a mutable HTTP request object, can modify headers/body/URI, and the driver auto-serializes
+824:the request body to JSON after all interceptors have run.
+825:
+826:For the full specification of how interceptors should behave, see the
+827:link:https://tinkerpop.apache.org/docs/x.y.z/dev/provider/#_http_request_interceptor[HTTP Request Interceptor]
+828:section in the provider documentation.
+829:
+830:===== match() Support
+831:
+832:The new `match(String)` step represents TinkerPop's first explicit extension point for provider-native query languages.
+833:Graph systems that support a declarative query language can now expose it directly through the standard Gremlin
+834:traversal API, making the language a first-class citizen of any `g.` chain rather than a parallel API that users have to
+835:context-switch into.
+836:
+837:The mechanism follows the same provider extension pattern used elsewhere in TinkerPop: `gremlin-core` inserts a
+838:placeholder step (`DeclarativeMatchStep`) into the traversal, and graph providers replace it with a concrete
+839:implementation via a `ProviderOptimizationStrategy`. The placeholder carries everything the provider needs:
+840:
+841:* `getMatchQuery()` — the raw query string as written by the user
+842:* `getParams()` — the bound parameter map from the `match(String, Map)` overload, or `null`
+843:* `getQueryLanguage()` — the explicit language hint from `with("queryLanguage", ...)`, or `null` meaning "use your native language"
+844:* `isStart()` — `true` when the step was invoked as a spawn step on `GraphTraversalSource`
+845:
+846:For each result row the concrete step must:
+847:
+848:* Set the traverser value to a `Map<String, Object>` keyed by named variable name, containing one entry per bound
+849: variable in the row. Anonymous elements must not appear in the map.
+850:* Record each named variable in the traverser's path history via `addLabels()`, so downstream `select()` steps
+851: can retrieve values by name.
+852:* Declare `TraverserRequirement.LABELED_PATH` in `getRequirements()`.
+853:
+854:Providers that want to use TinkerPop's built-in GQL engine rather than supplying their own step can add the
+855:`gql-gremlin` module and register `GqlDeclarativeMatchStrategy.instance()` in their graph's global strategy
+856:cache. The singleton lazily allocates a `DefaultGqlPlanner` and `DefaultGqlExecutor` per graph instance on
+857:first use and caches them for the lifetime of the graph, sharing the planner's query parse cache across all
+858:traversals. Optional performance hints are available via `countVerticesByLabel()`, `countEdgesByLabel()`,
+859:and `Graph.Index`. See `GqlMatchStep` and `GqlDeclarativeMatchStrategy` in `gql-gremlin` for the complete
+860:reference implementation, and the
+861:link:https://tinkerpop.apache.org/docs/x.y.z/dev/provider/#tinkerpop-providers-tinkergql[provider documentation]
+862:for wiring instructions.
+863:
+864:== TinkerPop 4.0.0-beta.2
+865:
+866:*Release Date: April 1, 2026*
+867:
+868:Please see the link:https://github.com/apache/tinkerpop/blob/4.0.0-beta.2/CHANGELOG.asciidoc#release-4-0-0-beta-2[changelog] for a
+869:complete list of all the modifications that are part of this release.
+870:
+871:=== Upgrading for Users
+872:
+873:==== Python Property Access
+874:
+875:The `Element` class in `gremlin-python` now supports `__contains__` and `keys()`, enabling more idiomatic Python
+876:patterns for working with element properties. You can now use the `in` operator to check for property existence and
+877:`keys()` to retrieve the set of property names:
+878:
+879:[source,python]
+880:----
+881:v = g.V().has('person','name','stephen').next()
+882:
+883:# check if a property exists
+884:if "age" in v:
+885: print(v["age"])
+886:
+887:# get all property keys
+888:print(v.keys()) # {'name', 'age'}
+889:----
+890:
+891:See: link:https://issues.apache.org/jira/browse/TINKERPOP-3119[TINKERPOP-3119]
+892:
+893:==== Runtime Upgrades
+894:
+895:All JavaScript projects (`gremlin-javascript`, `gremlin-mcp`, `gremlint`) have been upgraded to node version 22.
+896:
+897:==== ResultQueue Removed
+898:
+899:The public class `ResultQueue` in `gremlin-driver` has been removed. Its functionality has been merged into
+900:`ResultSet`. Users of this class should reference the newly added methods of `ResultSet` instead.
+901:
+902:==== neo4j-gremlin Removed
+903:
+904:The module `neo4j-gremlin` was deprecated in 3.7.0 and has now been removed. It was based on version 3.4 of Neo4j which
+905:reached EOL in March 2020. Users that depend on this module will need to stay on the 3.x line.
+906:
+907:==== Gremlin MCP Server
+908:
+909:===== Gremlin Query Translation
+910:
+911:A `translate_gremlin_query` tool is now available that translates a Gremlin query into a target language variant.
+912:Supported targets are `canonical`, `javascript`, `python`, `go`, `dotnet`, `java`, `groovy`, and `anonymized`.
+913:
+914:The optional `source` parameter describes the dialect of the input. When omitted or set to `auto`, the server
+915:normalizes the input before translating — first by applying mechanical transformations (stripping language-specific
+916:prefixes, correcting step casing, etc.) and then by requesting LLM normalization from the MCP client via MCP
+917:sampling. If the MCP client does not support sampling, the LLM step is skipped gracefully and a warning is included
+918:in the response. Set `source` to `canonical` to bypass normalization entirely when the input is already in canonical
+919:gremlin-language ANTLR format.
+920:
+921:Some example prompts that will invoke this tool:
+922:
+923:[source,text]
+924:----
+925:Translate g.V().has('name','Alice').out('knows').values('name') to Python.
+926:----
+927:
+928:[source,text]
+929:----
+930:Convert this Go Gremlin traversal to Groovy:
+931:gremlingo.T__.V().Has("name", "Alice").Out("knows").Values("name")
+932:----
+933:
+934:[source,text]
+935:----
+936:I have some Java Gremlin code. Translate it to canonical format so I can review it:
+937:g.V().has("name", "Alice").out("knows").values("name")
+938:----
+939:
+940:===== Offline Mode
+941:
+942:`GREMLIN_MCP_ENDPOINT` is no longer required to start the server. When no endpoint is configured, graph tools
+943:(`get_graph_status`, `get_graph_schema`, `run_gremlin_query`) are not registered, but the utility tools
+944:(`translate_gremlin_query`, `format_gremlin_query`) remain fully available. This makes it possible to use the
+945:Gremlin MCP Server purely as a translation and formatting aid without any graph database:
+946:
+947:[source,text]
+948:----
+949:Format this Gremlin query for readability:
+950:g.V().has('name','Alice').out('knows').out('knows').where(neq('Alice')).values('name').dedup()
+951:----
+952:
+953:==== SLF4j 2.x
+954:
+955:TinkerPop has generally upgraded to SLF4j 2.x which brings with it some important changes to log initialization which
+956:may affect user applications that are upgrading from TinkerPop 3.x. Please see the
+957:link:https://www.slf4j.org/faq.html[SLF4j FAQ] (specifically "What has changed in SLF4J version 2.0.0?") that explains
+958:the differences and how they might apply.
+959:
+960:[[canonical-gremlin]]
+961:==== Canonical Gremlin
+962:
+963:In previous versions, GLV drivers sent traversals to the server as serialized `Bytecode` objects. In 4.0, `Bytecode`
+964:has been replaced by `GremlinLang`, which produces a canonical Gremlin string along with a map of named parameters.
+965:"Canonical Gremlin" is the standard, language-neutral string representation of a traversal as defined by the ANTLR
+966:grammar in the `gremlin-language` module. Each GLV now builds this canonical string directly, and the server's
+967:`gremlin-lang` script engine parses it using the same grammar.
+968:
+969:This change means all drivers speak the same language on the wire. Request payloads are now human-readable strings
+970:rather than opaque binary bytecode, making it easier to debug, log, and reason about what is being sent to the server.
+971:When documentation or code refers to a "gremlin-lang string", "canonical Gremlin", or "canonical format", it means a
+972:traversal string that conforms to this ANTLR grammar.
+973:
+974:For a detailed explanation of canonical Gremlin with examples in each language, see
+975:link:https://tinkerpop.apache.org/docs/4.0.0-beta.2/reference/#canonical-gremlin-definition[Canonical Gremlin and GremlinLang]
+976:in the Reference Documentation.
+977:
+978:[[glv-driver-changes]]
+979:==== GLV Driver Changes
+980:
+981:All Gremlin Language Variant drivers have been updated with three major changes in TinkerPop 4.0:
+982:
+983:1. *WebSockets replaced by HTTP* — All drivers now communicate with Gremlin Server over HTTP/1.1 using POST requests.
+984: WebSocket-specific settings and classes have been removed. Connection URLs change from `ws://` to `http://` (or
+985: `wss://` to `https://`). HTTP connection pooling is handled by each language's standard HTTP library.
+986:
+987:2. *Bytecode replaced by GremlinLang* — Traversals are no longer serialized as `Bytecode` objects. Instead, each GLV
+988: produces a <<canonical-gremlin, canonical Gremlin>> string via `GremlinLang`, which is sent to the server along with
+989: a parameter map. This simplifies the wire protocol and makes request payloads human-readable.
+990:
+991:3. *Interceptor-based authentication* — With the move to HTTP, authentication is now handled per-request through
+992: HTTP headers rather than during a connection handshake. All drivers use request interceptors to add auth headers
+993: before each request is sent. Built-in interceptors are provided for two common scenarios:
+994: - `BasicAuth` — adds a standard HTTP Basic `Authorization` header (username/password). This replaces the previous
+995: constructor parameters or SASL authenticators used in 3.x.
+996: - `SigV4Auth` — signs requests using AWS Signature Version 4. The interceptor handles credential resolution
+997: (including automatic refresh for temporary credentials) and request signing transparently.
+998: Custom interceptors can also be written to support other authentication schemes your graph provider may require.
+999:
+1000:The .NET, Go, and JavaScript drivers are new to 4.0 in this release. The Java and Python drivers were updated in the
+1001:beta.1 release and are summarized at the end of this section; see the <<java-requestinterceptor, Java>> and
+1002:<<python-requestinterceptor, Python>> sections in the beta.1 upgrade notes for full details.
+1003:
+1004:[[dotnet-http-interceptor]]
+1005:==== .NET
+1006:
+1007:The .NET driver (`Gremlin.Net`) has been updated to use HTTP. Connection URLs should be updated from `ws://` to
+1008:`http://` (or `wss://` to `https://`). The following settings have changed:
+1009:
+1010:- `ConnectionPoolSettings` — replaced with `ConnectionSettings` for HTTP connection configuration.
+1011:- `webSocketConfiguration` — removed.
+1012:- `sessionId` — removed.
+1013:- `disableCompression` — removed. Use `ConnectionSettings.EnableCompression` instead.
+1014:- `username` and `password` on `GremlinServer` — removed.
+1015:- `requestSerializer` and `responseSerializer` — can now be set independently on `GremlinClient`.
+1016:- `GraphBinaryMessageSerializer` — replaced with `GraphBinary4MessageSerializer`.
+1017:- `ConnectionPool` and `WebSocketConnection` — removed. HTTP connection pooling is managed by `SocketsHttpHandler`.
+1018:- Transaction support over HTTP is not yet implemented and `Tx()` will throw `NotSupportedException`.
+1019:
+1020:Authentication in 3.x was configured with `username` and `password` on the `GremlinServer` constructor. In 4.0, use
+1021:the `Auth` static methods via the `interceptors` parameter instead:
+1022:
+1023:[source,csharp]
+1024:----
+1025:// 3.x — credentials on GremlinServer (no longer supported)
+1026:// var server = new GremlinServer("localhost", 8182, true, "username", "password");
+1027:
+1028:// 4.0 — Basic authentication via interceptor
+1029:var server = new GremlinServer("localhost", 8182, enableSsl: true);
+1030:var client = new GremlinClient(server,
+1031: connectionSettings: new ConnectionSettings { SkipCertificateValidation = true },
+1032: interceptors: new[] { Auth.BasicAuth("username", "password") });
+1033:
+1034:// 4.0 — SigV4 authentication via interceptor
+1035:var server = new GremlinServer("localhost", 8182, enableSsl: true);
+1036:var client = new GremlinClient(server,
+1037: interceptors: new[] { Auth.SigV4Auth("service-region", "service-name") });
+1038:----
+1039:
+1040:Setting `requestSerializer` to `null` prevents the `RequestMessage` from being serialized before interceptors run,
+1041:allowing an interceptor to handle serialization and set the `Content-Type` header directly.
+1042:
+1043:[[go-http-interceptor]]
+1044:==== Go
+1045:
+1046:The Go driver (`gremlin-go`) has been updated to use HTTP. Connection URLs should be updated from `ws://` to
+1047:`http://` (or `wss://` to `https://`). The following settings have changed:
+1048:
+1049:- `AuthInfo` — removed.
+1050:- `TransporterType`, `ReadBufferSize`, `WriteBufferSize`, `WriteDeadline`, `NewConnectionThreshold` — removed.
+1051:- `Session` — removed.
+1052:- `MaximumConcurrentConnections`, `MaxIdleConnections`, `IdleConnectionTimeout`, `KeepAliveInterval` — added for HTTP
+1053: connection pool configuration.
+1054:
+1055:Authentication in 3.x was configured with the `AuthInfo` setting. In 4.0, use the `BasicAuth()` and `SigV4Auth()`
+1056:interceptors instead:
+1057:
+1058:[source,go]
+1059:----
+1060:// 3.x — AuthInfo setting (no longer supported)
+1061:// settings.AuthInfo = gremlingo.BasicAuthInfo("username", "password")
+1062:
+1063:// 4.0 — Basic authentication via interceptor
+1064:remote, err := gremlingo.NewDriverRemoteConnection("https://localhost:8182/gremlin",
+1065: func(settings *gremlingo.DriverRemoteConnectionSettings) {
+1066: settings.RequestInterceptors = []gremlingo.RequestInterceptor{
+1067: gremlingo.BasicAuth("username", "password"),
+1068: }
+1069: })
+1070:
+1071:// 4.0 — SigV4 authentication via interceptor
+1072:remote, err := gremlingo.NewDriverRemoteConnection("https://localhost:8182/gremlin",
+1073: func(settings *gremlingo.DriverRemoteConnectionSettings) {
+1074: settings.RequestInterceptors = []gremlingo.RequestInterceptor{
+1075: gremlingo.SigV4Auth("service-region", "service-name"),
+1076: }
+1077: })
+1078:----
+1079:
+1080:[[javascript-typescript-esm]]
+1081:==== JavaScript
+1082:
+1083:The JavaScript driver (`gremlin-javascript`) has been rewritten in TypeScript, migrated to HTTP, and now ships with
+1084:built-in type declarations and dual ESM/CommonJS builds. Connection URLs should be updated from `ws://` to `http://`
+1085:(or `wss://` to `https://`). The following settings have changed:
+1086:
+1087:- `mimeType` — removed. Use `reader` and `writer` options directly.
+1088:- `authenticator` — removed.
+1089:- `session` — removed.
+1090:- `interceptors` — added to `Client` and `DriverRemoteConnection` for HTTP request modification.
+1091:- `writer` — can be set to `null` to skip request serialization, allowing interceptors to handle it directly.
+1092:- `bulkResults` — added as a request option. `DriverRemoteConnection` defaults it to `true`.
+1093:
+1094:Authentication in 3.x was configured with the `authenticator` option. In 4.0, use `auth.basic()` and `auth.sigv4()`
+1095:instead:
+1096:
+1097:[source,javascript]
+1098:----
+1099:import gremlin from 'gremlin';
+1100:const { DriverRemoteConnection, auth } = gremlin.driver;
+1101:
+1102:// 3.x — PlainTextSaslAuthenticator (no longer supported)
+1103:// const authenticator = new gremlin.driver.auth.PlainTextSaslAuthenticator('user', 'pass');
+1104:// new DriverRemoteConnection('ws://localhost:8182/gremlin', { authenticator });
+1105:
+1106:// 4.0 — Basic authentication via interceptor
+1107:const connection = new DriverRemoteConnection('https://localhost:8182/gremlin', {
+1108: interceptors: auth.basic('username', 'password'),
+1109:});
+1110:
+1111:// 4.0 — SigV4 authentication via interceptor
+1112:// Requires @smithy/signature-v4 and @smithy/hash-node packages
+1113:const connection = new DriverRemoteConnection('https://localhost:8182/gremlin', {
+1114: interceptors: auth.sigv4('service-region', 'service-name'),
+1115:});
+1116:----
+1117:
+1118:===== TypeScript and Module Format
+1119:
+1120:The package now sets `"type": "module"` in `package.json` and uses conditional `exports`:
+1121:
+1122:- ESM: `import gremlin from 'gremlin'` resolves to `build/esm/index.js`
+1123:- CJS: `const gremlin = require('gremlin')` resolves to `build/cjs/index.cjs`
+1124:
+1125:Existing CommonJS applications using `require('gremlin')` continue to work without changes:
+1126:
+1127:[source,javascript]
+1128:----
+1129:// CommonJS (still works)
+1130:const gremlin = require('gremlin');
+1131:
+1132:// ESM — default import
+1133:import gremlin from 'gremlin';
+1134:
+1135:// ESM — named imports
+1136:import { driver, process, structure } from 'gremlin';
+1137:----
+1138:
+1139:Type declarations (`.d.ts`) are included in the published package. TypeScript projects can import the driver directly
+1140:without installing separate `@types` packages:
+1141:
+1142:[source,typescript]
+1143:----
+1144:import gremlin from 'gremlin';
+1145:import type { ConnectionOptions } from 'gremlin/build/esm/driver/connection.js';
+1146:
+1147:const connection = new gremlin.driver.DriverRemoteConnection('http://localhost:8182/gremlin');
+1148:const g = gremlin.process.traversal().with_(connection);
+1149:----
+1150:
+1151:===== Breaking Export Changes
+1152:
+1153:Several exports have been removed or renamed compared to 3.x:
+1154:
+1155:- `process.Bytecode` — removed. Use `process.GremlinLang` instead.
+1156:- `process.Translator` — removed. Use `process.GremlinLang` instead (e.g. `traversal.getGremlinLang().getGremlin()`).
+1157:- `driver.auth.Authenticator` and `driver.auth.PlainTextSaslAuthenticator` — removed. Use `driver.auth.basic()` and
+1158: `driver.auth.sigv4()` instead.
+1159:- `structure.io` — removed. Serialization is now internal to the driver.
+1160:- `Graph.traversal()` — removed. Use `process.traversal()` instead.
+1161:
+1162:==== Java
+1163:
+1164:The Java driver (`gremlin-driver`) was the first to adopt HTTP in the beta.1 release. Connection URLs should be
+1165:updated from `ws://` to `http://` (or `wss://` to `https://`). The following settings have changed:
+1166:
+1167:- `enableCompression` — removed.
+1168:- `bulkResults` — added. See <<result-bulking-from-server, Result Bulking from Server>> for details.
+1169:- `maxContentLength` — renamed to `maxResponseContentLength`. Now limits total response size.
+1170:- `minConnectionPoolSize` — removed. Connections are now closed based on `idleConnectionTimeout` rather than usage
+1171: thresholds. Multiple connections can be opened concurrently to support bursty workloads.
+1172:
+1173:Authentication in 3.x was configured with `credentials()` on the `Cluster` builder. In 4.0, pass `Auth.basic()` or
+1174:`Auth.sigv4()` to the builder's `auth()` method instead:
+1175:
+1176:[source,java]
+1177:----
+1178:// 3.x — credentials on Cluster builder (no longer supported)
+1179:// Cluster cluster = Cluster.build("localhost").credentials("username", "password").create();
+1180:
+1181:// 4.0 — Basic authentication
+1182:Cluster cluster = Cluster.build("localhost").auth(Auth.basic("username", "password")).create();
+1183:
+1184:// 4.0 — SigV4 authentication
+1185:Cluster cluster = Cluster.build("localhost").auth(Auth.sigv4("service-region", "service-name")).create();
+1186:----
+1187:
+1188:For advanced use cases, HTTP interceptors can be configured on `Cluster` using `addInterceptor`,
+1189:`addInterceptorBefore`, `addInterceptorAfter`, and `removeInterceptor`. Each interceptor requires a name for ordering
+1190:and receives an `HttpRequest` containing the request method, URI, headers, and body. A default "serializer"
+1191:interceptor handles serialization of the `RequestMessage` into the format the server expects.
+1192:
+1193:[source,java]
+1194:----
+1195:Cluster cluster = Cluster.build("localhost")
+1196: .addInterceptor("myAuth", request -> {
+1197: request.getHeaders().put("Authorization", "Bearer my-token");
+1198: return request;
+1199: })
+1200: .create();
+1201:----
+1202:
+1203:==== Python
+1204:
+1205:The Python driver (`gremlin-python`) adopted HTTP in the beta.1 release. Connection URLs should be updated from
+1206:`ws://` to `http://` (or `wss://` to `https://`). The following settings have changed:
+1207:
+1208:- `enableCompression` — removed.
+1209:- `bulk_results` — added. See <<result-bulking-from-server, Result Bulking from Server>> for details.
+1210:- `message_serializer` — split into `request_serializer` and `response_serializer`.
+1211:- `username` and `password` — replaced with `auth`.
+1212:- `kerberized_service` — removed.
+1213:- `session` — removed.
+1214:
+1215:Authentication in 3.x was configured with `username` and `password` parameters on `DriverRemoteConnection`. In 4.0,
+1216:use the `auth` parameter with `basic()` or `sigv4()` from the `auth` module instead:
+1217:
+1218:[source,python]
+1219:----
+1220:from gremlin_python.driver.auth import basic, sigv4
+1221:
+1222:# 3.x — username/password parameters (no longer supported)
+1223:# g = traversal().with_(DriverRemoteConnection('ws://localhost:8182/gremlin', 'g',
+1224:# username='stephen', password='password'))
+1225:
+1226:# 4.0 — Basic authentication
+1227:g = traversal().with_(DriverRemoteConnection(
+1228: 'http://localhost:8182/gremlin', 'g', auth=basic('stephen', 'password')))
+1229:
+1230:# 4.0 — SigV4 authentication
+1231:g = traversal().with_(DriverRemoteConnection(
+1232: 'http://localhost:8182/gremlin', 'g', auth=sigv4('service-region', 'service-name')))
+1233:----
+1234:
+1235:HTTP interceptors can be passed to `DriverRemoteConnection` or `Client` using the `interceptors` parameter. An
+1236:interceptor is a `Callable` that receives the HTTP request dictionary (containing headers, payload, and auth). Setting
+1237:`request_serializer` to `None` prevents automatic serialization, allowing an interceptor to handle it directly.
+1238:
+1239:==== Transactions Re-enabled
+1240:
+1241:IMPORTANT: The remote transaction API is still under active discussion and the specification has not been finalized.
+1242:This implementation is experimental and subject to breaking changes in future releases. It is provided to enable early
+1243:feedback and testing, but should not be relied upon for production use until the specification is complete.
+1244:
+1245:The 4.0.0-beta.1 release disabled transactions and noted that `tx()` would return an error. Transactions have now been
+1246:re-enabled over HTTP for both Gremlin Server and the Java driver. The transaction model uses server-managed sessions
+1247:where each transaction is identified by a server-generated transaction ID that the client passes on subsequent requests.
+1248:
+1249:The basic lifecycle is: begin a transaction, submit one or more traversals within it, then commit or rollback. Data
+1250:written inside a transaction is isolated from other clients until committed.
+1251:
+1252:Transactions also work through `DriverRemoteConnection` with the familiar `g.tx()` pattern:
+1253:
+1254:[source,java]
+1255:----
+1256:final GraphTraversalSource g = traversal().with(DriverRemoteConnection.using(cluster, "g"));
+1257:final GraphTraversalSource gtx = g.tx().begin();
+1258:gtx.addV("person").iterate();
+1259:gtx.tx().commit();
+1260:----
+1261:
+1262:The `RemoteTransaction` can be used directly from `Cluster.transact()`:
+1263:
+1264:[source,java]
+1265:----
+1266:final Cluster cluster = Cluster.open();
+1267:
+1268:// begin, write, and commit
+1269:final RemoteTransaction tx = cluster.transact("g");
+1270:tx.begin();
+1271:tx.submit("g.addV('person').property('name','alice')");
+1272:tx.commit();
+1273:----
+1274:
+1275:The `RemoteTransaction` also supports configurable close behavior. By default, `close()` commits the transaction. To
+1276:rollback on close instead:
+1277:
+1278:[source,java]
+1279:----
+1280:final RemoteTransaction tx = cluster.transact("g");
+1281:tx.onClose(Transaction.CLOSE_BEHAVIOR.ROLLBACK);
+1282:tx.begin();
+1283:tx.submit("g.addV('person')");
+1284:tx.close(); // rolls back instead of committing
+1285:----
+1286:
+1287:NOTE: The current implementation creates a dedicated HTTP connection pool per transaction. Connection sharing between
+1288:requests will be improved in the final release for better resource efficiency and performance.
+1289:
+1290:=== Upgrading for Providers
+1291:
+1292:==== Graph System Providers
+1293:
+1294:===== Java-based Test Suite
+1295:
+1296:The traditional Java-based "process" test suite has been removed. It was deprecated in 3.8.0, with the instruction to
+1297:move to the more comprehensive, language agnostic, Gherkin test framework which now unifies all Gremlin semantics
+1298:testing. This unified approach to testing with Gherkin provides the easiest way to ensure that the same Gremlin
+1299:semantics are applied for both graph systems and for Gremlin Language Variants, with the additional benefit that its
+1300:easy-to-read format is well suited to LLMs.
+1301:
+1302:TinkerPop does retain a small cohort of Java-based "process" tests for embedded graphs wishing to validate some
+1303:additional features that are not well suited to the Gherkin style. Providers who wish to use these simply implement the
+1304:`ProcessEmbeddedStandardSuite` and the `ProcessEmbeddedComputerSuite` as has normally been done in the past.
+1305:
+1306:== TinkerPop 4.0.0-beta.1
+1307:
+1308:*Release Date: January 17, 2025*
+1309:
+1310:Please see the link:https://github.com/apache/tinkerpop/blob/4.0.0-beta.1/CHANGELOG.asciidoc#release-4-0-0-beta-1[changelog] for a
+1311:complete list of all the modifications that are part of this release.
+1312:
+1313:NOTE: 4.0.0-beta.1 is a beta/milestone release. It is meant as a preview version to try out the new HTTP API
+1314:features in the server and drivers (Java/Python only). As this is a beta version only, you can expect breaking changes to
+1315:occur in future betas for 4.0.0 on the way to its General Availability release. Items that have important
+1316:limitations and constraints pertinent to this beta will be highlighted through the documentation inside an
+1317:"IMPORTANT" box that starts with "4.0 Beta Release".
+1318:
+1319:=== Upgrading for Users
+1320:
+1321:[[result-bulking-from-server]]
+1322:==== Result Bulking from Server
+1323:In previous versions, when a traversal is submitted through the DriverRemoteConnection (DRC) via the Bytecode processor,
+1324:the results from the server were bulked as Traverser, which provides a form of result optimization across the wire.
+1325:Starting with 4.0, with the removal of Bytecode and Traverser serializer, this optimization is now achieved via
+1326:`GraphBinaryV4` response message serialization, and can be controlled through cluster setting or per request option.
+1327:
+1328:Per request option setting will always override cluster settings, and regardless of cluster or request option settings,
+1329:bulking will only occur if the script processing language is set to `gremlin-lang` and the serializer is set to `GraphBinaryV4`.
+1330:
+1331:[source,java]
+1332:----
+1333:// cluster setting
+1334:Cluster cluster = Cluster.build().bulkResults(true).create();
+1335:
+1336:// per request option
+1337:GraphTraversalSource g = traversal().with(DriverRemoteConnection.using(cluster));
+1338:List result = g.with("language", "gremlin-lang").with("bulkResults", true).inject(1).toList();
+1339:----
+1340:
+1341:By default, the cluster setting of `bulkResults` is false. To remain consistent with previous behavior, remote traversal
+1342:submitted through the DRC will always send a request option setting `bulkResults` to `true`. This implies that if `gremlin-lang`
+1343:script engine and `GraphBinaryV4` serializer are used, then server will bulk results before sending regardless of cluster setting,
+1344:and can only be disabled via per request option.
+1345:
+1346:==== BulkSet Behavior Changes
+1347:Starting with 4.0, steps which return BulkSet (e.g. `aggregate()`) will have results returned in different format
+1348:depending on embedded or remote usage.
+1349:
+1350:For embedded cases, a BulkSet will be returned as before.
+1351:
+1352:For remote cases, BulkSets will now be expanded into Lists upon deserialization with `gremlin-driver`. All other GLVs
+1353:already expanded BulkSet to List prior to TinkerPop 4. Each element in the BulkSet will appear in the list the same
+1354:number of times as specified by its bulk value.
+1355:
+1356:==== Configuration Changes
+1357:
+1358:The following configuration changes were introduced in the beta.1 release for Gremlin Server, Java, and Python. For
+1359:.NET, Go, and JavaScript configuration changes, see <<glv-driver-changes, GLV Driver Changes>> in the section above.
+1360:
+1361:* Gremlin Server
+1362:** `maxContentLength` setting has been renamed to `maxRequestContentLength`.
+1363:* Java GLV
+1364:** `enableCompression` setting has been removed.
+1365:** `bulkResults` has been added. See <<result-bulking-from-server, result bulking>> for more details.
+1366:** `maxContentLength` setting has been renamed to `maxResponseContentLength` and now blocks incoming responses that are
+1367:too large based on total response size.
+1368:** `addInterceptorAfter`, `addInterceptorBefore`, `addInterceptor` and `removeInterceptor` have been added.
+1369:See <<java-requestinterceptor, Changes to Java RequestInterceptor>> for more details.
+1370:* Python GLV
+1371:** `enableCompression` setting has been removed.
+1372:** `bulk_results` has been added. See <<result-bulking-from-server, result bulking>> for more details.
+1373:** `interceptors` has been added to the Python GLV to modify HTTP requests. See
+1374:<<python-requestinterceptor, Addition of Python interceptor>> for more details.
+1375:** `message_serializer` setting has been separated into `request_serializer` and `response_serializer`. See
+1376:<<python-requestinterceptor, Addition of Python interceptor>> for more details.
+1377:** `username` and `password` settings for the Python GLV has been replaced with `auth`.
+1378:** `kerberized_service` setting has been removed.
+1379:** `session` setting has been removed.
+1380:
+1381:==== Console Command Removals
+1382:
+1383:The `:remote` and `:submit` commands, used to establish connections and send scripts to a remote `gremlin-server`, are
+1384:no longer supported in `gremlin-console`. If sending a traversal, users should instead create a `RemoteTraversalSource`
+1385:(see <<simplified-g-creation, Simplification to g Creation for examples>>).
+1386:
+1387:While a `RemoteTraversalSource` is the preferred method of executing remote traversals from `gremlin-console`, it
+1388:remains possible to send scripts directly using a `gremlin-driver` `Client`.
+1389:
+1390:[source,groovy]
+1391:----
+1392:cluster = Cluster.open('conf/remote.yaml')
+1393:client = cluster.connect()
+1394:
+1395:client.submit("g.V()")
+1396:
+1397:client.close()
+1398:cluster.close()
+1399:----
+1400:
+1401:==== Removal of Gephi Console Plugin
+1402:
+1403:The Gephi Plugin for `gremlin-console` is no longer supported and has been removed. Apache TinkerPop no longer maintains
+1404:any graph visualization tool, however there are a number of community-led alternatives available, many of which are
+1405:listed on the link:https://tinkerpop.apache.org/community.html#powered-by[TinkerPop community page].
+1406:
+1407:[[java-requestinterceptor]]
+1408:==== Java RequestInterceptor
+1409:
+1410:Because the underlying transport has been changed from WebSockets to HTTP, the usage of the `RequestInterceptor` has
+1411:changed as well. The `RequestInterceptor` will now be run per request and will allow you to completely modify the HTTP
+1412:request that is sent to the server. `Cluster` has four new methods added to it: `addInterceptorAfter`,
+1413:`addInterceptorBefore`, `removeInterceptor` and `addInterceptor`. Each interceptor requires a name as it will be used
+1414:to insert new interceptors in different positions.
+1415:
+1416:The interceptors work with a new class called HttpRequest. This is just a basic abstraction over a request but it also
+1417:contains some useful strings for common headers. The initial `HttpRequest` that is passed to the first interceptor will
+1418:contain a `RequestMessage`. `RequestMessage` is immutable and only certain keys can be added to them. If you want to
+1419:customize the body by adding other fields, you will need to make a different copy of the `RequestMessage` or completely
+1420:change the body to contain a different data type. The final interceptor must return a `HttpRequest` whose body contains
+1421:a `byte[]`.
+1422:
+1423:After the initial HTTP request is generated, the interceptors will be called in order to allow the request to be
+1424:modified. After each `RequestInterceptor` is run, the request is updated with the data from the final `HttpRequest` and
+1425:that is sent to the endpoint. There is a default interceptor added to every `Cluster` called "serializer". This
+1426:interceptor is responsible for serializing the request body is which what the server normally expects. This is intended
+1427:to be an advanced customization technique that should only be used when needed.
+1428:
+1429:[[python-requestinterceptor]]
+1430:==== Python Interceptor
+1431:
+1432:HTTP interceptors have been added to `gremlin-python` to enable capability similar to that of Java GLV. These
+1433:interceptors can be passed into either a `DriverRemoteConnection` or a `Client` using the interceptors parameter. An
+1434:interceptor is a `Callable` that accepts one argument which is the HTTP request (dictionary containing header, payload
+1435:and auth) or a list/tuple of these functions. The interceptors will run after the request serializer has run but before
+1436:any auth functions run so the HTTP request may still get modified after your interceptors are run. In situations where
+1437:you don't want the payload to be serialized, the `message_serializer` has been split into a `request_serializer` and a
+1438:`response_serializer`. Simply set the `request_serializer` to `None` and this will prevent the `RequestMessage` from
+1439:being serialized. Again, this is expected to be an advanced feature so some knowledge of implementation details will be
+1440:required to make this work. For example, you'll need to know what payload formats are accepted by `aiohttp` for the
+1441:request to be sent.
+1442:
+1443:==== JavaScript Set Deserialization
+1444:
+1445:Starting from this version, `gremlin-javascript` will deserialize `Set` data into an ECMAScript 2015 `Set`. Previously,
+1446:these were deserialized into arrays.
+1447:
+1448:==== Gremlin Grammar Changes
+1449:
+1450:A number of changes have been introduced to the Gremlin grammar to help make it be more consistent and easier to use.
+1451:
+1452:*`new` keyword is now optional*
+1453:
+1454:The `new` keyword is now optional in all cases where it was previously used. Both of the following examples are now
+1455:valid syntax with the second being the preferred form going forward:
+1456:
+1457:[source,groovy]
+1458:----
+1459:g.V().withStrategies(new SubgraphStrategy(vertices: __.hasLabel('person')))
+1460:
+1461:g.V().withStrategies(SubgraphStrategy(vertices: __.hasLabel('person')))
+1462:----
+1463:
+1464:In a future version, it is likely that the `new` keyword will be removed entirely from the grammar.
+1465:
+1466:*Refined variable support*
+1467:
+1468:The Gremlin grammar allows variables to be used in various places. Unlike Groovy, from which the Gremlin grammar is
+1469:partially derived and which allows variables to be used for any argument to a method, Gremlin only allows for variables
+1470:to be used when they refer to particular types. In making this change it did mean that all enums like, `Scope`, `Pop`,
+1471:`Order`, etc. can no longer be used in that way and can therefore only be recognized as literal values.
+1472:
+1473:*Supports withoutStrategies()*
+1474:
+1475:The `withoutStrategies()` configuration step is now supported syntax for the grammar. While this option is not commonly
+1476:used it is still a part of the Gremlin language and there are times where it is helpful to have this fine grained
+1477:control over how a traversal works.
+1478:
+1479:[source,groovy]
+1480:----
+1481:g.V().withoutStrategies(CountStrategy)
+1482:----
+1483:
+1484:See: link:https://issues.apache.org/jira/browse/TINKERPOP-2862[TINKERPOP-2862],
+1485:link:https://issues.apache.org/jira/browse/TINKERPOP-3046[TINKERPOP-3046]
+1486:
+1487:==== Renamed none() to discard()
+1488:
+1489:The `none()` step, which was primarily used by `iterate()` to discard traversal results in remote contexts, has been
+1490:renamed to `discard()`. In its place is a new list filtering step `none()`, which takes a predicate as an argument and
+1491:passes lists with no elements matching the predicate.
+1492:
+1493:==== Integer Overflow Handling
+1494:
+1495:Integer overflows caused by addition and multiplication operations will throw an exception instead of being silently
+1496:skipped with incorrect result.
+1497:
+1498:==== SeedStrategy Construction
+1499:
+1500:The `SeedStrategy` public constructor has been removed for Java and has been replaced by the builder pattern common
+1501:to all strategies. This change was made to ensure that the `SeedStrategy` could be constructed in a consistent manner.
+1502:
+1503:==== Removal of `gremlin-archetype`
+1504:
+1505:`gremlin-archetype`, which contained example projects demonstrating the use cases of TinkerPop, has been removed in
+1506:favor of newer sample applications which can be found in each GLV's `examples` folder.
+1507:
+1508:==== Improved Translators
+1509:
+1510:The various Java `Translator` implementations allowing conversion of Gremlin traversals to string forms in various
+1511:languages have been modified considerably. First, they have been moved from to the
+1512:`org.apache.tinkerpop.gremlin.language.translator` package, because they now depend on the ANTLR grammar in
+1513:`gremlin-language` to handled the translation process. Making this change allowed for a more accurate translation of
+1514:Gremlin that doesn't need to rely on reflection and positional arguments to determine which step was intended for use.
+1515:
+1516:Another important change was the introduction of specific translators for Groovy and Java. While Groovy translation
+1517:tends to work for most Java cases, there is syntax specific to Groovy where it does not. With a specific Java
+1518:translator, the translation process can be more accurate and less error prone.
+1519:
+1520:The syntax for the translators has simplified as well. The translator function now takes a Gremlin string and a target
+1521:language to translate to. Consider the following example:
+1522:
+1523:[source,text]
+1524:----
+1525:gremlin> GremlinTranslator.translate("g.V().out('knows')", Translator.GO)
+1526:==>g.V().Out("knows")
+1527:----
+1528:
+1529:Further note that Gremlin language variants produce <<canonical-gremlin, canonical Gremlin>> strings directly since
+1530:bytecode was removed. As a result, all translators in .NET, Python, Go and Javascript have been removed.
+1531:
+1532:See: link:https://issues.apache.org/jira/browse/TINKERPOP-3028[TINKERPOP-3028]
+1533:
+1534:==== Python OptionsStrategy
+1535:
+1536:The `\\__init__()` syntax has been updated to be both more pythonic and more aligned to the `gremlin-lang` syntax.
+1537:Previously, `OptionsStrategy()` took a single argument `options` which was a `dict` of all options to be set.
+1538:Now, all options should be set directly as keyword arguments.
+1539:
+1540:For example:
+1541:
+1542:[source,python]
+1543:----
+1544:# 3.7 and before:
+1545:g.with_strategies(OptionsStrategy(options={'key1': 'value1', 'key2': True}))
+1546:# 4.x and newer:
+1547:g.with_strategies(OptionsStrategy(key1='value1', key2=True))
+1548:
+1549:myOptions = {'key1': 'value1', 'key2': True}
+1550:# 3.7 and before:
+1551:g.with_strategies(OptionsStrategy(options=myOptions))
+1552:# 4.x and newer:
+1553:g.with_strategies(OptionsStrategy(**myOptions))
+1554:----
+1555:
+1556:==== Custom Traversal Strategy Construction
+1557:
+1558:Traversal strategy construction has been updated such that it is no longer required to have concrete classes for each
+1559:strategy being added to a graph traversal (use of concrete classes remains viable and is recommended for "native"
+1560:TinkerPop strategies). To use strategies without a concrete class, `TraversalStrategyProxy` can be used in Java, and
+1561:`TraversalStrategy` in Python.
+1562:
+1563:All the following examples will produce the script `g.withStrategies(new MyStrategy(config1:'my value',config2:123))`:
+1564:
+1565:[source,java]
+1566:----
+1567:Map<String, Object> configMap = new LinkedHashMap<>();
+1568: configMap.put("config1", "my value");
+1569: configMap.put("config2", 123);
+1570: TraversalStrategy strategyProxy = new TraversalStrategyProxy("MyStrategy", new MapConfiguration(configMap));
+1571:
+1572: GraphTraversal traversal = g.withStrategies(strategyProxy);
+1573:----
+1574:
+1575:[source,python]
+1576:----
+1577:g.with_strategies(TraversalStrategy(
+1578: strategy_name='MyStrategy',
+1579: config1='my value',
+1580: config2=123
+1581: ))
+1582:----
+1583:
+1584:==== Serialization
+1585:
+1586:The GLVs will only support GraphBinaryV4 and GraphSON support will be removed. This means that the serializer option
+1587:that was available in most GLVs has been removed. GraphBinary is a more compact format and has support for the same
+1588:types. This should lead to increased performance for users upgrading from any version of GraphSON to GraphBinary.
+1589:
+1590:The number of serializable types has been reduced in V4. For example, only a single temporal type remains. You have two
+1591:options when trying to work with data types whose serializer has been removed: first, you can attempt to convert the
+1592:data to another type that still have a serializer or, second, the type may have been too specific and therefore removed
+1593:in which case your provider should have a Provider Defined Type (PDT) for it. See the next paragraph for information on
+1594:PDTs.
+1595:
+1596:Custom serializers have also been removed so if you previously included those as part of your application, they should
+1597:now be removed. In its place, PDTs have been introduced. In particular, there is the Primitive PDT and the Composite
+1598:PDT. Primitive PDTs are string-based representations of a primitive type supported by your provider. Composite types
+1599:contain a map of fields. You should consult your provider's documentation to determine what types of fields a
+1600:particular PDT may contain.
+1601:
+1602:==== Authentication and Authorization
+1603:
+1604:With the move to HTTP, the only authentication option supported out-of-the-box is HTTP basic access authentication
+1605:(username/password). The SASL-based authentication mechanisms are no longer supported (e.g. Kerberos). Your graph
+1606:system provider may choose to implement other authentication mechanisms over HTTP which you would have to use via a
+1607:request interceptor. Refer to your provider's documentation to determine if other authentication mechanisms are
+1608:available.
+1609:
+1610:==== Transactions Disabled
+1611:
+1612:IMPORTANT: 4.0.0-beta.1 Release - Transactions are currently disabled and use of `tx()` will return an error.
+1613:
+1614:==== Removal of Sessions
+1615:
+1616:Support for sessions has been removed. All requests are now "sessionless" with no shared state across subsequent requests.
+1617:
+1618:==== Result Bulking Changes
+1619:
+1620:Previous versions of the Gremlin Server would attempt to "bulk" the result if bytecode was used in the request. This
+1621:"bulking" increased performance by sending similar results once with a count of occurrences. Starting in 4.0, Gremlin
+1622:Server will bulk based on a newly introduced `bulked` field in the `RequestMessage`. It only applies to GraphBinary and
+1623:`gremlin-lang` requests and other requests won't be bulked. This can be toggled in the language variants by setting a
+1624:boolean value with `enableBulkedResult()` in the `Cluster` settings.
+1625:
+1626:==== Gremlin Java Changes
+1627:
+1628:Connection pooling has been updated to work with HTTP. Previously, connections could only be opened one at a time, but
+1629:this has changed and now many connections can be opened at the same time. This supports bursty workloads where many
+1630:queries may be issued within a short period of time. Connections are no longer closed based on how "busy" they are
+1631:based on the `minInProcessPerConnection` and `minSimultaneousUsagePerConnection`, rather they are closed based on an
+1632:idle timeout called `idleConnectionTimeout`. Because the number of connections can increase much faster and connections
+1633:are closed based on a timeout, the `minConnectionPoolSize` option has been removed and there may be zero connections
+1634:available if the driver has been idle for a while.
+1635:
+1636:The Java driver can currently handle a response that is a maximum of 2^31-1 (`Integer.MAX_VALUE`) bytes in size.
+1637:Queries that return more data will have to be separated into multiple queries that return less data.
+1638:
+1639:==== GValue
+1640:
+1641:Parameterization was first added to gremlin-lang in TinkerPop 3.7.0, however was limited in that variables were
+1642:immediately resolved to literals during the compilation of a gremlin script. This direct resolution of variables limited
+1643:providers ability to detect and optimize recurring query patterns.
+1644:
+1645:With this update, a new class `GValue` is introduced which wraps a parameter name and value. Steps which will benefit
+1646:from parameterization have been given overloads to accept GValues. Users can pass GValue's into their traversals to
+1647:inject parameters.
+1648:
+1649:A `GValue` wraps a parameter name and value, and can be provided as input to parameterizable steps when building a
+1650:`GraphTraversal`. The following examples will produce a gremlin script of `g.V().hasLabel(label)` with a parameter map
+1651:of `["label": "person"]`:
+1652:
+1653:[source,java]
+1654:----
+1655:g.V().hasLabel(GValue.of("label", "person"));
+1656:----
+1657:
+1658:[source,python]
+1659:----
+1660:g.V().has_label(GValue('label', 'person'))
+1661:----
+1662:
+1663:Use of `GValue` in traversals with repeated patterns may lead to improved performance in certain graphs. Consult the
+1664:documentation for your specific graph provider for recommendations on how to best utilize `GValue` in traversals.
+1665:
+1666:A new `DefaultVariableResolver` has also been introduced with this change. The grammar will now resolve variables into
+1667:`GValue` which are passed to the constructed traversal, instead of directly resolving them to literals. The old variable
+1668:resolution behavior can still be obtained via the `DirectVariableResolver` if desired.
+1669:
+1670:==== Gremlin Server Default Language
+1671:
+1672:`gremlin-lang` is now the default language and script engine in Gremlin-Server, replacing `gremlin-groovy`. Users may
+1673:still explicitly set the `language` field of a request message to `"gremlin-groovy"` in cases where groovy scripts are
+1674:required.
+1675:
+1676:=== Upgrading for Providers
+1677:
+1678:==== Renaming NoneStep to DiscardStep
+1679:NoneStep, which was primarily used by `iterate()` to discard traversal results in remote contexts, has been renamed to
+1680:DiscardStep. In its place is a new list filtering NoneStep, which takes a predicate as an argument and passes lists with
+1681:no elements matching the predicate.
+1682:
+1683:==== Changes to Serialization
+1684:
+1685:The V4 versions of GraphBinary and GraphSON are being introduced. Support for the older versions of GraphBinary (V1)
+1686:and GraphSON (V1-3) is removed. Upon the full release of 4.0, the GLVs will only use GraphBinary, however, the Gremlin
+1687:Server will support both GraphSON and GraphBinary. The following is a list of the major changes to the GraphBinary
+1688:format:
+1689:
+1690:* Removed type serializers:
+1691:** Period
+1692:** Date
+1693:** TimeStamp
+1694:** Instant
+1695:** ZonedDateTime
+1696:** OffsetTime
+1697:** LocalDateTime
+1698:** LocalDate
+1699:** LocalTime
+1700:** MonthDay
+1701:** YearMonth
+1702:** Year
+1703:** ZoneOffset
+1704:** BulkSet
+1705:** Class
+1706:** Binding
+1707:** Bytecode
+1708:** Barrier
+1709:** Cardinality
+1710:** Column
+1711:** Operator
+1712:** Order
+1713:** Pick
+1714:** Pop
+1715:** Scope
+1716:** DT
+1717:** Lambda
+1718:** P
+1719:** Traverser
+1720:** TextP
+1721:** TraversalStrategy
+1722:** Metrics
+1723:** TraversalMetrics
+1724:** InetAddress
+1725:* OffsetDatetime has been renamed to Datetime. This type maps to `OffsetDateTime` in Java and a `datetime` in Python.
+1726:* Byte is redefined from being unsigned byte to a signed byte.
+1727:* List has a `0x02` value_flag used to denote bulking.
+1728:* Map has a `0x02` value_flag used to denote ordering.
+1729:* `Element` (Vertex, Edge, VertexProperty) labels have been changed from `String` to `List` of `String`.
+1730:* `Element` (Vertex, Edge, VertexProperty) properties are no longer null and are `List` of `Property`.
+1731:* Custom is replaced with Provider Defined Types
+1732:
+1733:One of the biggest differences is in datetime support. Previously, in the Java implementation, `java.util.Date`,
+1734:`java.sql.Timestamp` and most types from the `java.time` package had serializers. This isn't the case in GraphSON 4
+1735:as only `java.time.OffsetDateTime` is supported. Java provides methods to convert amongst these classes so they should
+1736:be used to convert your data to and from `java.time.OffsetDateTime`.
+1737:
+1738:The `GraphSONSerializerProvider` is not used in GraphSON 4. The `GraphSONSerializerProvider` uses the
+1739:`ToStringSerializer` for any unknown type and was used in previous GraphSON versions. Because GraphSON 4 is only
+1740:intended to serialize specific types and not used as a general serializer, GraphSON 4 serializers will throw an error
+1741:when encountering unknown types.
+1742:
+1743:==== Graph System Providers
+1744:
+1745:===== AbstractAuthenticatorHandler Constructor
+1746:
+1747:The deprecated one-arg constructor for `AbstractAuthenticationHandler` has been removed along with two-arg constructors
+1748:for the implementations. Gremlin Server formerly supported the two-arg `Authenticator`, and `Settings` constructor for
+1749:instantiating new custom instances. It now expects implementations of `AbstractAuthenticationHandler` to use a
+1750:three-arg constructor that takes `Authenticator`, `Authorizer`, and `Settings`.
+1751:
+1752:===== GraphManager Changes
+1753:
+1754:The `beforeQueryStart()`, `onQueryError()`, and `onQuerySuccess()` of `GraphManager` have been removed. These were
+1755:originally intended to give providers more insight into when execution occurs in the server and the outcome of that
+1756:execution. However, they depended on `RequestMessage` containing a Request ID, which isn't the case anymore.
+1757:
+1758:===== Gremlin Server Updates
+1759:
+1760:The `OpProcessor` extension point of the server has been removed. In order to extend the functionality of the Gremlin
+1761:Server, you have to implement your own `Channelizer`.
+1762:
+1763:If you are a provider that makes use of the Gremlin Server, you may need to update server configuration YAML files that
+1764:you provide to your users. With the change from WebSockets to HTTP, some of the previous default values are invalid and
+1765:some of the fields no longer exist. See link:https://tinkerpop.apache.org/docs/4.0.0/reference/#_configuring_2[options]
+1766:for an updated list. One of the most important changes is to the `Channelizer` configuration as only the
+1767:`HttpChannelizer` remains and the rest have been removed.
+1768:
+1769:===== Gremlin Server Default Language
+1770:
+1771:`gremlin-lang` is now the default language and script engine in Gremlin-Server, replacing `gremlin-groovy`. Users may
+1772:still explicitly set the `language` field of a request message to `"gremlin-groovy"` in cases where groovy scripts are
+1773:required.
+1774:
+1775:==== Graph Driver Providers
+1776:
+1777:===== Application Layer Protocol Support
+1778:
+1779:HTTP/1.1 is now the only supported application-layer protocol and WebSockets support is dropped. Please follow the
+1780:instructions in the
+1781:link:https://tinkerpop.apache.org/docs/4.0.0/dev/provider/#_graph_driver_provider_requirements[provider documentation]
+1782:for more detailed information. The subprotocol remains fairly similar but has been adjusted to work better with HTTP.
+1783:Also, the move to HTTP means that SASL has been removed as an authentication mechanism and only HTTP basic remains.
+1784:
+1785:===== Request Interceptor
+1786:
+1787:It is strongly recommended that every graph driver provider give a way for users to intercept and modify the HTTP
+1788:request before it is sent off to the server. This capability is needed in cases where the graph system provider has
+1789:additional functionality that can be enabled by modifying the HTTP request.
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/TraversalStrategies.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/TraversalStrategies.java
index bccb983665..509b9b7d8d 100644
--- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/TraversalStrategies.java
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/TraversalStrategies.java
@@ -54,6 +54,7 @@ import org.apache.tinkerpop.gremlin.process.traversal.strategy.optimization.Prod
import org.apache.tinkerpop.gremlin.process.traversal.strategy.optimization.RepeatUnrollStrategy;
import org.apache.tinkerpop.gremlin.process.traversal.strategy.verification.ComputerVerificationStrategy;
import org.apache.tinkerpop.gremlin.process.traversal.strategy.verification.EdgeLabelVerificationStrategy;
+import org.apache.tinkerpop.gremlin.process.traversal.strategy.verification.LabelsDropVerificationStrategy;
import org.apache.tinkerpop.gremlin.process.traversal.strategy.verification.LambdaRestrictionStrategy;
import org.apache.tinkerpop.gremlin.process.traversal.strategy.verification.ReadOnlyStrategy;
import org.apache.tinkerpop.gremlin.process.traversal.strategy.verification.ReservedKeysVerificationStrategy;
@@ -263,6 +264,7 @@ public interface TraversalStrategies extends Serializable, Cloneable, Iterable<T
// verification
put(EdgeLabelVerificationStrategy.class.getSimpleName(), EdgeLabelVerificationStrategy.class);
+ put(LabelsDropVerificationStrategy.class.getSimpleName(), LabelsDropVerificationStrategy.class);
put(LambdaRestrictionStrategy.class.getSimpleName(), LambdaRestrictionStrategy.class);
put(ReadOnlyStrategy.class.getSimpleName(), ReadOnlyStrategy.class);
put(ReservedKeysVerificationStrategy.class.getSimpleName(), ReservedKeysVerificationStrategy.class);
@@ -287,6 +289,7 @@ public interface TraversalStrategies extends Serializable, Cloneable, Iterable<T
LazyBarrierStrategy.instance(),
ProfileStrategy.instance(),
StandardVerificationStrategy.instance(),
+ LabelsDropVerificationStrategy.instance(),
GValueReductionStrategy.instance());
registerStrategies(Graph.class, graphStrategies);
registerStrategies(EmptyGraph.class, new DefaultTraversalStrategies());
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/AbstractAddVertexStepPlaceholder.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/AbstractAddVertexStepPlaceholder.java
index 3e0f0c1c0f..f14e9998d0 100644
--- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/AbstractAddVertexStepPlaceholder.java
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/AbstractAddVertexStepPlaceholder.java
@@ -57,6 +57,12 @@ public abstract class AbstractAddVertexStepPlaceholder<S> extends AbstractAddEle
return Vertex.DEFAULT_LABEL;
}
+ @Override
+ public void setLabel(Object label) {
+ super.setLabel(label);
+ userProvidedLabel = true;
+ }
+
@Override
public boolean hasUserProvidedLabel() {
return userProvidedLabel;
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/AddVertexStartStep.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/AddVertexStartStep.java
index 5f109ae426..4e256fc96b 100644
--- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/AddVertexStartStep.java
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/AddVertexStartStep.java
@@ -53,24 +53,27 @@ public class AddVertexStartStep extends AbstractStep<Vertex, Vertex> implements
public AddVertexStartStep(final Traversal.Admin traversal, final String label) {
super(traversal);
- this.internalParameters.set(this, T.label, null == label ? Vertex.DEFAULT_LABEL : label);
+ if (label != null) {
+ this.internalParameters.set(this, T.label, label);
+ }
userProvidedLabel = label != null;
}
public AddVertexStartStep(final Traversal.Admin traversal, final Traversal<?, String> vertexLabelTraversal) {
super(traversal);
- this.internalParameters.set(this, T.label, null == vertexLabelTraversal ? Vertex.DEFAULT_LABEL : vertexLabelTraversal);
+ if (vertexLabelTraversal != null) {
+ this.internalParameters.set(this, T.label, vertexLabelTraversal);
+ }
userProvidedLabel = vertexLabelTraversal != null;
}
public AddVertexStartStep(final Traversal.Admin traversal, final Set<String> labels) {
super(traversal);
- if (labels == null || labels.isEmpty()) {
- this.internalParameters.set(this, T.label, Vertex.DEFAULT_LABEL);
- userProvidedLabel = false;
- } else {
+ if (labels != null && !labels.isEmpty()) {
this.internalParameters.set(this, T.label, labels);
userProvidedLabel = true;
+ } else {
+ userProvidedLabel = false;
}
}
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/AddVertexStartStepPlaceholder.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/AddVertexStartStepPlaceholder.java
index a1b5fa2449..24c25d3ad4 100644
--- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/AddVertexStartStepPlaceholder.java
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/AddVertexStartStepPlaceholder.java
@@ -19,7 +19,6 @@
package org.apache.tinkerpop.gremlin.process.traversal.step.map;
import org.apache.tinkerpop.gremlin.process.traversal.Traversal;
-import org.apache.tinkerpop.gremlin.process.traversal.lambda.ConstantTraversal;
import org.apache.tinkerpop.gremlin.process.traversal.step.GValue;
import org.apache.tinkerpop.gremlin.process.traversal.step.GValueHolder;
import org.apache.tinkerpop.gremlin.structure.Vertex;
@@ -30,16 +29,15 @@ public class AddVertexStartStepPlaceholder extends AbstractAddVertexStepPlacehol
implements AddVertexStepContract<Vertex>, GValueHolder<Vertex, Vertex> {
public AddVertexStartStepPlaceholder(final Traversal.Admin traversal, final String label) {
- super(traversal, label == null ? Vertex.DEFAULT_LABEL : label);
+ super(traversal, label);
}
public AddVertexStartStepPlaceholder(final Traversal.Admin traversal, final GValue<String> label) {
- super(traversal, label == null ? GValue.of(Vertex.DEFAULT_LABEL) : label);
+ super(traversal, label);
}
public AddVertexStartStepPlaceholder(final Traversal.Admin traversal, final Traversal.Admin<?,String> vertexLabelTraversal) {
- super(traversal, vertexLabelTraversal == null ?
- new ConstantTraversal<>(Vertex.DEFAULT_LABEL) : (Traversal.Admin<Vertex,String>) vertexLabelTraversal);
+ super(traversal, vertexLabelTraversal == null ? null : (Traversal.Admin<Vertex,String>) vertexLabelTraversal);
}
public AddVertexStartStepPlaceholder(final Traversal.Admin traversal, final Set<String> labels) {
@@ -56,7 +54,10 @@ public class AddVertexStartStepPlaceholder extends AbstractAddVertexStepPlacehol
} else if (label instanceof GValue) {
step = new AddVertexStartStep(traversal, ((GValue<String>) label).get());
} else {
- step = new AddVertexStartStep(traversal, (String) label);
+ // When userProvidedLabel is false, label may be the default from the placeholder
+ // hierarchy. Pass null so AddVertexStartStep does not inject T.label.
+ final String labelStr = hasUserProvidedLabel() ? (String) label : null;
+ step = new AddVertexStartStep(traversal, labelStr);
}
super.configureConcreteStep(step);
return step;
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/strategy/verification/LabelsDropVerificationStrategy.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/strategy/verification/LabelsDropVerificationStrategy.java
new file mode 100644
index 0000000000..b13a5b1526
--- /dev/null
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/strategy/verification/LabelsDropVerificationStrategy.java
@@ -0,0 +1,66 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tinkerpop.gremlin.process.traversal.strategy.verification;
+
+import org.apache.tinkerpop.gremlin.process.traversal.Step;
+import org.apache.tinkerpop.gremlin.process.traversal.Traversal;
+import org.apache.tinkerpop.gremlin.process.traversal.TraversalStrategy;
+import org.apache.tinkerpop.gremlin.process.traversal.step.filter.DropStep;
+import org.apache.tinkerpop.gremlin.process.traversal.step.filter.FilterStep;
+import org.apache.tinkerpop.gremlin.process.traversal.step.map.LabelsStep;
+import org.apache.tinkerpop.gremlin.process.traversal.strategy.AbstractTraversalStrategy;
+import org.apache.tinkerpop.gremlin.process.traversal.util.TraversalHelper;
+
+/**
+ * Prevents {@code labels().drop()} patterns in traversals. Users should use
+ * {@code dropLabel(label)} or {@code dropLabels()} instead.
+ *
+ * @since 4.0.0
+ */
+public final class LabelsDropVerificationStrategy
+ extends AbstractTraversalStrategy<TraversalStrategy.VerificationStrategy>
+ implements TraversalStrategy.VerificationStrategy {
+
+ private static final LabelsDropVerificationStrategy INSTANCE = new LabelsDropVerificationStrategy();
+
+ private LabelsDropVerificationStrategy() {
+ }
+
+ @Override
+ public void apply(final Traversal.Admin<?, ?> traversal) {
+ for (final DropStep<?> dropStep : TraversalHelper.getStepsOfClass(DropStep.class, traversal)) {
+ Step<?, ?> current = dropStep.getPreviousStep();
+
+ // Walk backward through filter steps (IsStep, HasStep, WhereStep, NotStep, etc.)
+ while (current instanceof FilterStep) {
+ current = current.getPreviousStep();
+ }
+
+ if (current instanceof LabelsStep) {
+ throw new VerificationException(
+ "labels().drop() is not supported. Use dropLabel(label) or dropLabels() instead.",
+ traversal);
+ }
+ }
+ }
+
+ public static LabelsDropVerificationStrategy instance() {
+ return INSTANCE;
+ }
+}
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/Graph.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/Graph.java
index d0453be36c..6166193a6f 100644
--- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/Graph.java
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/Graph.java
@@ -742,11 +742,11 @@ public interface Graph extends AutoCloseable, Host {
* Gets the {@link LabelCardinality} for vertices in this graph. Defines how many labels
* a vertex can have and whether labels are mutable.
*
- * @return the label cardinality for vertices, defaulting to {@link LabelCardinality#ZERO_OR_MORE}
+ * @return the label cardinality for vertices, defaulting to {@link LabelCardinality#ONE}
* @since 4.0.0
*/
default LabelCardinality getLabelCardinality() {
- return LabelCardinality.ZERO_OR_MORE;
+ return LabelCardinality.ONE;
}
/**
@@ -809,25 +809,14 @@ public interface Graph extends AutoCloseable, Host {
}
/**
- * Gets the {@link LabelCardinality} for edges in this graph. Defines how many labels
- * an edge can have and whether labels are mutable.
+ * Gets the {@link LabelCardinality} for edges in this graph. Edge labels are always
+ * immutable (exactly one label, set at creation time).
*
- * @return the label cardinality for edges, defaulting to {@link LabelCardinality#ZERO_OR_ONE}
+ * @return the label cardinality for edges, always {@link LabelCardinality#ONE}
* @since 4.0.0
*/
default LabelCardinality getLabelCardinality() {
- return LabelCardinality.ZERO_OR_ONE;
- }
-
- /**
- * Gets the default label returned for edges with no explicit labels when the cardinality
- * requires at least one label ({@link LabelCardinality#ONE} or {@link LabelCardinality#ONE_OR_MORE}).
- *
- * @return the default edge label, typically {@link Edge#DEFAULT_LABEL}
- * @since 4.0.0
- */
- default String getDefaultLabel() {
- return Edge.DEFAULT_LABEL;
+ return LabelCardinality.ONE;
}
}
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/util/detached/DetachedVertex.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/util/detached/DetachedVertex.java
index 977eb8ebcc..b4ae187bc2 100644
--- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/util/detached/DetachedVertex.java
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/util/detached/DetachedVertex.java
@@ -128,7 +128,7 @@ public class DetachedVertex extends DetachedElement<Vertex> implements Vertex {
if (this.vertexLabels != null && !this.vertexLabels.isEmpty()) {
return this.vertexLabels.iterator().next();
}
- return this.label != null ? this.label : Vertex.DEFAULT_LABEL;
+ return this.label != null ? this.label : "";
}
@Override
diff --git a/gremlin-core/src/test/java/org/apache/tinkerpop/gremlin/process/traversal/strategy/verification/LabelsDropVerificationStrategyTest.java b/gremlin-core/src/test/java/org/apache/tinkerpop/gremlin/process/traversal/strategy/verification/LabelsDropVerificationStrategyTest.java
new file mode 100644
index 0000000000..eefe785c2b
--- /dev/null
+++ b/gremlin-core/src/test/java/org/apache/tinkerpop/gremlin/process/traversal/strategy/verification/LabelsDropVerificationStrategyTest.java
@@ -0,0 +1,85 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tinkerpop.gremlin.process.traversal.strategy.verification;
+
+import org.apache.tinkerpop.gremlin.process.traversal.P;
+import org.apache.tinkerpop.gremlin.process.traversal.Traversal;
+import org.apache.tinkerpop.gremlin.process.traversal.TraversalStrategies;
+import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__;
+import org.apache.tinkerpop.gremlin.process.traversal.util.DefaultTraversalStrategies;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+
+import java.util.Arrays;
+
+import static org.junit.Assert.fail;
+
+/**
+ * Tests for {@link LabelsDropVerificationStrategy}.
+ * Verifies that {@code labels().drop()} patterns are rejected while unrelated patterns are allowed.
+ */
+@RunWith(Parameterized.class)
+public class LabelsDropVerificationStrategyTest {
+
+ @Parameterized.Parameters(name = "{0}")
+ public static Iterable<Object[]> data() {
+ return Arrays.asList(new Object[][]{
+ // Should REJECT: labels() followed by drop() (possibly with filter steps in between)
+ {"labels().drop()", __.labels().drop(), false},
+ {"labels().is('x').drop()", __.labels().is("x").drop(), false},
+ {"labels().where(P.eq('x')).drop()", __.labels().where(P.eq("x")).drop(), false},
+ {"labels().not(__.is('x')).drop()", __.labels().not(__.is("x")).drop(), false},
+
+ // Should ALLOW: no LabelsStep before drop
+ {"V().drop()", __.V().drop(), true},
+ {"properties().drop()", __.properties().drop(), true},
+
+ // Should ALLOW: non-filter step between labels() and drop() breaks the walk
+ {"labels().map(__.constant('x')).drop()", __.labels().map(__.constant("x")).drop(), true},
+ {"labels().order().drop()", __.labels().order().drop(), true},
+ });
+ }
+
+ @Parameterized.Parameter(value = 0)
+ public String name;
+
+ @Parameterized.Parameter(value = 1)
+ public Traversal.Admin traversal;
+
+ @Parameterized.Parameter(value = 2)
+ public boolean allow;
+
+ @Test
+ public void shouldVerifyLabelsDropPattern() {
+ final TraversalStrategies strategies = new DefaultTraversalStrategies();
+ strategies.addStrategies(LabelsDropVerificationStrategy.instance());
+ traversal.asAdmin().setStrategies(strategies);
+ if (allow) {
+ traversal.asAdmin().applyStrategies();
+ } else {
+ try {
+ traversal.asAdmin().applyStrategies();
+ fail("The strategy should not allow labels().drop() pattern: " + name);
+ } catch (VerificationException ve) {
+ // expected
+ }
+ }
+ }
+}
diff --git a/gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Gherkin/CommonSteps.cs b/gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Gherkin/CommonSteps.cs
index 2c42d1a8be..9729e7f419 100644
--- a/gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Gherkin/CommonSteps.cs
+++ b/gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Gherkin/CommonSteps.cs
@@ -105,13 +105,27 @@ namespace Gremlin.Net.IntegrationTest.Gherkin
[Given("the (\\w+) graph")]
public void ChooseModernGraph(string graphName)
{
- if (graphName == "empty")
+ var isMultiLabel = ScenarioData.CurrentScenario != null &&
+ (ScenarioData.CurrentScenario.Tags.Any(t => t.Name == "@MultiLabel") ||
+ (ScenarioData.CurrentFeature != null && ScenarioData.CurrentFeature.Tags.Any(t => t.Name == "@MultiLabel")));
+
+ if (isMultiLabel && graphName == "empty")
+ {
+ ScenarioData.CleanMultilabelData();
+ var data = ScenarioData.GetByGraphName("multilabel");
+ _graphName = "multilabel";
+ _g = Traversal().With(data.Connection);
+ }
+ else
{
- ScenarioData.CleanEmptyData();
+ if (graphName == "empty")
+ {
+ ScenarioData.CleanEmptyData();
+ }
+ var data = ScenarioData.GetByGraphName(graphName);
+ _graphName = graphName;
+ _g = Traversal().With(data.Connection);
}
- var data = ScenarioData.GetByGraphName(graphName);
- _graphName = graphName;
- _g = Traversal().With(data.Connection);
}
[Given("using the parameter (\\w+) defined as \"(.*)\"")]
@@ -159,11 +173,15 @@ namespace Gremlin.Net.IntegrationTest.Gherkin
Gremlin.UseTraversal(ScenarioData.CurrentScenario!.Name, _g, _parameters, _sideEffects);
traversal.Iterate();
- // We may have modified the so-called `empty` graph
+ // We may have modified the so-called `empty` or `multilabel` graph
if (_graphName == "empty")
{
ScenarioData.ReloadEmptyData();
}
+ else if (_graphName == "multilabel")
+ {
+ ScenarioData.ReloadMultilabelData();
+ }
}
[Given("an unsupported test")]
diff --git a/gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Gherkin/GherkinTestRunner.cs b/gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Gherkin/GherkinTestRunner.cs
index 04969b5fae..6aee902762 100644
--- a/gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Gherkin/GherkinTestRunner.cs
+++ b/gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Gherkin/GherkinTestRunner.cs
@@ -125,12 +125,6 @@ namespace Gremlin.Net.IntegrationTest.Gherkin
continue;
}
- if (scenario.Tags.Any(t => t.Name == "@MultiLabel"))
- {
- failedSteps.Add(scenario.Steps.First(), new IgnoreException(IgnoreReason.MultiLabelStepsNotSupported));
- continue;
- }
-
StepBlock? currentStep = null;
StepDefinition? stepDefinition = null;
foreach (var step in scenario.Steps)
diff --git a/gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Gherkin/Gremlin.cs b/gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Gherkin/Gremlin.cs
index 1b876c1baa..5728b738ba 100644
--- a/gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Gherkin/Gremlin.cs
+++ b/gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Gherkin/Gremlin.cs
@@ -1253,7 +1253,6 @@ namespace Gremlin.Net.IntegrationTest.Gherkin
{"g_V_valuesXnameX_lTrim", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.AddV((string) "person").Property("name", " marko ").Property("age", 29).As("marko").AddV((string) "person").Property("name", " vadas ").Property("age", 27).As("vadas").AddV((string) "software").Property("name", " lop").Property("lang", "java").As("lop").AddV((string) "person").Property("name", "josh ").Property("age", 32).As("josh").AddV((string) "softwar [...]
{"g_V_valuesXnameX_order_fold_lTrimXlocalX", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.AddV((string) "person").Property("name", " marko ").Property("age", 29).As("marko").AddV((string) "person").Property("name", " vadas ").Property("age", 27).As("vadas").AddV((string) "software").Property("name", " lop").Property("lang", "java").As("lop").AddV((string) "person").Property("name", "josh ").Property("age", 32).As("josh").AddV [...]
{"g_V_hasLabelXpersonX_labels", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.V().HasLabel("person").Labels()}},
- {"g_addVXa_bX_labels_fold", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.AddV((string) "a", (string) "b"), (g,p) =>g.V().Labels().Fold()}},
{"g_addVXa_bX_labels_count", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.AddV((string) "a", (string) "b"), (g,p) =>g.V().Labels().Count()}},
{"g_addV_labels", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.AddV(), (g,p) =>g.V().Labels()}},
{"g_E_labels", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.E().HasLabel("knows").Labels()}},
@@ -1525,12 +1524,13 @@ namespace Gremlin.Net.IntegrationTest.Gherkin
{"g_injectXlist1_list2_list3X_fold_asXmX_mergeVXselectXmX_limitXlocal_1X_unfoldX_optionXonCreate_selectXmX_rangeXlocal_1_2X_unfoldX_optionXonMatch_selectXmX_tailXlocalX_unfoldX_to_create", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.AddV((string) "person").Property("name", "marko").Property("age", 29), (g,p) =>g.Inject<object>(new Dictionary<object, object> {{ T.Label, "person" }, { "name", "stephen" }}, new Dictionary<object, o [...]
{"g_mergeVXlabel_ab_name_markoX_multilabel_create", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.MergeV((IDictionary<object, object>) new Dictionary<object, object> {{ T.Label, new List<object> { "person", "employee" } }, { "name", "marko" }}), (g,p) =>g.V(), (g,p) =>g.V().HasLabel("person").HasLabel("employee"), (g,p) =>g.V().Has("name", "marko")}},
{"g_mergeVXlabel_abc_name_testX_multilabel_create", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.MergeV((IDictionary<object, object>) new Dictionary<object, object> {{ T.Label, new List<object> { "a", "b", "c" } }, { "name", "test" }}), (g,p) =>g.V(), (g,p) =>g.V().HasLabel("a").HasLabel("b").HasLabel("c")}},
- {"g_mergeVXlabel_person_name_markoX_single_label", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.MergeV((IDictionary<object, object>) new Dictionary<object, object> {{ T.Label, "person" }, { "name", "marko" }}), (g,p) =>g.V(), (g,p) =>g.V().HasLabel("person"), (g,p) =>g.V().Has("name", "marko")}},
{"g_mergeVXlabel_ab_name_markoX_multilabel_match", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.AddV((string) "person").AddLabel("employee").Property("name", "marko"), (g,p) =>g.MergeV((IDictionary<object, object>) new Dictionary<object, object> {{ T.Label, new List<object> { "person", "employee" } }, { "name", "marko" }}), (g,p) =>g.V(), (g,p) =>g.V().HasLabel("person").HasLabel("employee")}},
{"g_mergeVXlabel_ab_name_markoX_multilabel_nomatch", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.AddV((string) "person").Property("name", "marko"), (g,p) =>g.MergeV((IDictionary<object, object>) new Dictionary<object, object> {{ T.Label, new List<object> { "person", "employee" } }, { "name", "marko" }}), (g,p) =>g.V()}},
{"g_mergeVXlabel_person_name_markoX_optionXonMatch_label_managerX", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.AddV((string) "person").AddLabel("employee").Property("name", "marko"), (g,p) =>g.MergeV((IDictionary<object, object>) new Dictionary<object, object> {{ T.Label, "person" }, { "name", "marko" }}).Option(Merge.OnMatch, (IDictionary<object, object>) new Dictionary<object, object> {{ T.Label, "manager" }}), (g,p) =>g.V(), [...]
{"g_mergeVXlabel_person_name_markoX_optionXonMatch_label_manager_directorX", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.AddV((string) "person").Property("name", "marko"), (g,p) =>g.MergeV((IDictionary<object, object>) new Dictionary<object, object> {{ T.Label, "person" }, { "name", "marko" }}).Option(Merge.OnMatch, (IDictionary<object, object>) new Dictionary<object, object> {{ T.Label, new List<object> { "manager", "director" [...]
{"g_mergeVXlabel_person_name_markoX_optionXonMatch_label_emptyX", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.AddV((string) "person").Property("name", "marko"), (g,p) =>g.MergeV((IDictionary<object, object>) new Dictionary<object, object> {{ T.Label, "person" }, { "name", "marko" }}).Option(Merge.OnMatch, (IDictionary<object, object>) new Dictionary<object, object> {{ T.Label, new List<object> { } }}), (g,p) =>g.V(), (g,p) =>g. [...]
+ {"g_mergeVXname_markoX_optionXonCreate_label_ab_name_markoX", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.MergeV((IDictionary<object, object>) new Dictionary<object, object> {{ "name", "marko" }}).Option(Merge.OnCreate, (IDictionary<object, object>) new Dictionary<object, object> {{ T.Label, new List<object> { "person", "employee" } }, { "name", "marko" }}), (g,p) =>g.V(), (g,p) =>g.V().HasLabel("person").HasLabel("employee"), ( [...]
+ {"g_mergeVXlabel_person_name_markoX_optionXonMatch_label_existingX", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.AddV((string) "person").AddLabel("employee").Property("name", "marko"), (g,p) =>g.MergeV((IDictionary<object, object>) new Dictionary<object, object> {{ T.Label, "person" }, { "name", "marko" }}).Option(Merge.OnMatch, (IDictionary<object, object>) new Dictionary<object, object> {{ T.Label, "person" }}), (g,p) =>g.V(), [...]
{"g_V_age_min", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.V().Values<object>("age").Min<object>()}},
{"g_V_foo_min", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.V().Values<object>("foo").Min<object>()}},
{"g_V_name_min", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.V().Values<object>("name").Min<object>()}},
@@ -2083,6 +2083,7 @@ namespace Gremlin.Net.IntegrationTest.Gherkin
{"g_V_dropLabels_defaultLabel", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.AddV((string) "person"), (g,p) =>g.V().DropLabels().Labels()}},
{"g_E_dropLabelXknowsX_labels", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.AddV((string) "person").As("a").AddV((string) "person").As("b").AddE((string) "knows").From("a").To("b"), (g,p) =>g.E().DropLabel("knows").Labels().Fold()}},
{"g_E_dropLabels_labels", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.AddV((string) "person").As("a").AddV((string) "person").As("b").AddE((string) "knows").From("a").To("b"), (g,p) =>g.E().DropLabels().Labels()}},
+ {"g_V_dropLabelXnonExistentX_labels", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.AddV((string) "a", (string) "b"), (g,p) =>g.V().DropLabel("xyz").Labels()}},
{"g_V_fail", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.V().Fail()}},
{"g_V_failXmsgX", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.V().Fail("msg")}},
{"g_V_unionXout_failX", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.V().Union<object>(__.Out(), __.Fail())}},
diff --git a/gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Gherkin/IgnoreException.cs b/gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Gherkin/IgnoreException.cs
index bf3918f253..7001391004 100644
--- a/gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Gherkin/IgnoreException.cs
+++ b/gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Gherkin/IgnoreException.cs
@@ -70,11 +70,6 @@ namespace Gremlin.Net.IntegrationTest.Gherkin
/// <summary>
/// write() is not supported yet for testing
/// </summary>
- WriteStepTestingNotSupported,
-
- /// <summary>
- /// Multi-label steps (labels(), addLabel(), dropLabel(), dropLabels()) are not yet available in the .NET GLV
- /// </summary>
- MultiLabelStepsNotSupported
+ WriteStepTestingNotSupported
}
}
\ No newline at end of file
diff --git a/gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Gherkin/ScenarioData.cs b/gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Gherkin/ScenarioData.cs
index 708b3db978..6644934ef8 100644
--- a/gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Gherkin/ScenarioData.cs
+++ b/gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Gherkin/ScenarioData.cs
@@ -74,6 +74,12 @@ namespace Gremlin.Net.IntegrationTest.Gherkin
g.V().Drop().Iterate();
}
+ public void CleanMultilabelData()
+ {
+ var g = Traversal().With(GetByGraphName("multilabel").Connection);
+ g.V().Drop().Iterate();
+ }
+
public void ReloadEmptyData()
{
var graphData = _dataPerGraph["empty"];
@@ -83,6 +89,15 @@ namespace Gremlin.Net.IntegrationTest.Gherkin
graphData.VertexProperties = GetVertexProperties(g);
}
+ public void ReloadMultilabelData()
+ {
+ var graphData = _dataPerGraph["multilabel"];
+ var g = Traversal().With(graphData.Connection);
+ graphData.Vertices = GetVertices(g);
+ graphData.Edges = GetEdges(g);
+ graphData.VertexProperties = GetVertexProperties(g);
+ }
+
private readonly IDictionary<string, ScenarioDataPerGraph> _dataPerGraph;
public ScenarioData(IMessageSerializer messageSerializer)
@@ -92,6 +107,9 @@ namespace Gremlin.Net.IntegrationTest.Gherkin
var empty = new ScenarioDataPerGraph("empty", _connectionFactory.CreateRemoteConnection("ggraph"),
new Dictionary<string, Vertex>(0), new Dictionary<string, Edge>(), new Dictionary<string, VertexProperty>());
_dataPerGraph.Add("empty", empty);
+ var multilabel = new ScenarioDataPerGraph("multilabel", _connectionFactory.CreateRemoteConnection("gmultilabel"),
+ new Dictionary<string, Vertex>(0), new Dictionary<string, Edge>(), new Dictionary<string, VertexProperty>());
+ _dataPerGraph.Add("multilabel", multilabel);
}
private Dictionary<string, ScenarioDataPerGraph> LoadDataPerGraph()
diff --git a/gremlin-go/driver/cucumber/cucumberSteps_test.go b/gremlin-go/driver/cucumber/cucumberSteps_test.go
index 6cbf768215..669933f429 100644
--- a/gremlin-go/driver/cucumber/cucumberSteps_test.go
+++ b/gremlin-go/driver/cucumber/cucumberSteps_test.go
@@ -501,10 +501,23 @@ func (tg *tinkerPopGraph) nothingShouldHappenBecause(arg1 *godog.DocString) erro
// Choose the graph.
func (tg *tinkerPopGraph) chooseGraph(graphName string) error {
- tg.graphName = graphName
- data := tg.graphDataMap[graphName]
+ // Multi-label tests use the gmultilabel traversal source for empty graphs
+ isMultiLabel := false
+ for _, tag := range tg.scenario.Tags {
+ if tag.Name == "@MultiLabel" {
+ isMultiLabel = true
+ break
+ }
+ }
+
+ if isMultiLabel && graphName == "empty" {
+ tg.graphName = "multilabel"
+ } else {
+ tg.graphName = graphName
+ }
+ data := tg.graphDataMap[tg.graphName]
tg.g = gremlingo.Traversal_().With(data.connection).With("language", "gremlin-lang")
- if graphName == "empty" {
+ if tg.graphName == "empty" || tg.graphName == "multilabel" {
err := tg.cleanEmptyDataGraph(tg.g)
if err != nil {
return err
@@ -994,6 +1007,8 @@ func (tg *tinkerPopGraph) theTraversalOf(arg1 *godog.DocString) error {
func (tg *tinkerPopGraph) usingTheParameterDefined(name string, params string) error {
if tg.graphName == "empty" {
tg.reloadEmptyData()
+ } else if tg.graphName == "multilabel" {
+ tg.reloadMultilabelData()
}
tg.parameters[name] = parseValue(strings.Replace(params, "\\\"", "\"", -1), tg.graphName)
return nil
@@ -1014,6 +1029,8 @@ func (tg *tinkerPopGraph) usingTheParameterOfP(paramName, pVal, stringVal string
func (tg *tinkerPopGraph) usingTheSideEffectDefined(key string, value string) error {
if tg.graphName == "empty" {
tg.reloadEmptyData()
+ } else if tg.graphName == "multilabel" {
+ tg.reloadMultilabelData()
}
tg.sideEffects[key] = parseValue(strings.Replace(value, "\\\"", "\"", -1), tg.graphName)
return nil
@@ -1129,7 +1146,7 @@ func TestCucumberFeatures(t *testing.T) {
TestSuiteInitializer: InitializeTestSuite,
ScenarioInitializer: InitializeScenario,
Options: &godog.Options{
- Tags: "~@GraphComputerOnly && ~@AllowNullPropertyValues && ~@StepTree && ~@StepWrite && ~@DataChar && ~@MultiLabel",
+ Tags: "~@GraphComputerOnly && ~@AllowNullPropertyValues && ~@StepTree && ~@StepWrite && ~@DataChar",
Format: "pretty",
Paths: []string{getEnvOrDefaultString("CUCUMBER_FEATURE_FOLDER", "../../../gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/test/features")},
TestingT: t, // Testing instance that will run subtests.
diff --git a/gremlin-go/driver/cucumber/cucumberWorld.go b/gremlin-go/driver/cucumber/cucumberWorld.go
index 206094522f..ecc50d34c5 100644
--- a/gremlin-go/driver/cucumber/cucumberWorld.go
+++ b/gremlin-go/driver/cucumber/cucumberWorld.go
@@ -87,7 +87,7 @@ func NewCucumberWorld() *CucumberWorld {
}
}
-var graphNames = []string{"modern", "classic", "crew", "grateful", "sink", "empty"}
+var graphNames = []string{"modern", "classic", "crew", "grateful", "sink", "empty", "multilabel"}
func (t *CucumberWorld) getDataGraphFromMap(name string) *DataGraph {
if val, ok := t.graphDataMap[name]; ok {
@@ -101,6 +101,8 @@ func (t *CucumberWorld) loadAllDataGraph() {
for _, name := range graphNames {
if name == "empty" {
t.loadEmptyDataGraph()
+ } else if name == "multilabel" {
+ t.loadMultilabelDataGraph()
} else {
connection, err := gremlingo.NewDriverRemoteConnection(scenarioUrl(),
func(settings *gremlingo.DriverRemoteConnectionSettings) {
@@ -128,6 +130,13 @@ func (t *CucumberWorld) loadEmptyDataGraph() {
t.graphDataMap["empty"] = &DataGraph{connection: connection}
}
+func (t *CucumberWorld) loadMultilabelDataGraph() {
+ connection, _ := gremlingo.NewDriverRemoteConnection(scenarioUrl(), func(settings *gremlingo.DriverRemoteConnectionSettings) {
+ settings.TraversalSource = "gmultilabel"
+ })
+ t.graphDataMap["multilabel"] = &DataGraph{connection: connection}
+}
+
func (t *CucumberWorld) reloadEmptyData() {
graphData := t.getDataGraphFromMap("empty")
g := gremlingo.Traversal_().With(graphData.connection).With("language", "gremlin-lang")
@@ -135,6 +144,13 @@ func (t *CucumberWorld) reloadEmptyData() {
graphData.edges = getEdges(g)
}
+func (t *CucumberWorld) reloadMultilabelData() {
+ graphData := t.getDataGraphFromMap("multilabel")
+ g := gremlingo.Traversal_().With(graphData.connection).With("language", "gremlin-lang")
+ graphData.vertices = getVertices(g)
+ graphData.edges = getEdges(g)
+}
+
func (t *CucumberWorld) cleanEmptyDataGraph(g *gremlingo.GraphTraversalSource) error {
future := g.V().Drop().Iterate()
return <-future
@@ -244,6 +260,10 @@ func (t *CucumberWorld) recreateAllDataGraphConnection() error {
t.getDataGraphFromMap(name).connection, err = gremlingo.NewDriverRemoteConnection(scenarioUrl(), func(settings *gremlingo.DriverRemoteConnectionSettings) {
settings.TraversalSource = "ggraph"
})
+ } else if name == "multilabel" {
+ t.getDataGraphFromMap(name).connection, err = gremlingo.NewDriverRemoteConnection(scenarioUrl(), func(settings *gremlingo.DriverRemoteConnectionSettings) {
+ settings.TraversalSource = "gmultilabel"
+ })
} else {
t.getDataGraphFromMap(name).connection, err = gremlingo.NewDriverRemoteConnection(scenarioUrl(), func(settings *gremlingo.DriverRemoteConnectionSettings) {
settings.TraversalSource = "g" + name
diff --git a/gremlin-go/driver/cucumber/gremlin.go b/gremlin-go/driver/cucumber/gremlin.go
index 14ca83bc81..a688116d6f 100644
--- a/gremlin-go/driver/cucumber/gremlin.go
+++ b/gremlin-go/driver/cucumber/gremlin.go
@@ -1223,7 +1223,6 @@ var translationMap = map[string][]func(g *gremlingo.GraphTraversalSource, p map[
"g_V_valuesXnameX_lTrim": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.AddV("person").Property("name", " marko ").Property("age", 29).As("marko").AddV("person").Property("name", " vadas ").Property("age", 27).As("vadas").AddV("software").Property("name", " lop").Property("lang", "java").As("lop").AddV("person").Property("name", "josh ").Property("age", 32).As("josh").AddV("software").Property("name", " ripple ").Proper [...]
"g_V_valuesXnameX_order_fold_lTrimXlocalX": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.AddV("person").Property("name", " marko ").Property("age", 29).As("marko").AddV("person").Property("name", " vadas ").Property("age", 27).As("vadas").AddV("software").Property("name", " lop").Property("lang", "java").As("lop").AddV("person").Property("name", "josh ").Property("age", 32).As("josh").AddV("software").Property("name", " [...]
"g_V_hasLabelXpersonX_labels": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.V().HasLabel("person").Labels()}},
- "g_addVXa_bX_labels_fold": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.AddV("a", "b")}, func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.V().Labels().Fold()}},
"g_addVXa_bX_labels_count": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.AddV("a", "b")}, func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.V().Labels().Count()}},
"g_addV_labels": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.AddV()}, func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.V().Labels()}},
"g_E_labels": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.E().HasLabel("knows").Labels()}},
@@ -1495,12 +1494,13 @@ var translationMap = map[string][]func(g *gremlingo.GraphTraversalSource, p map[
"g_injectXlist1_list2_list3X_fold_asXmX_mergeVXselectXmX_limitXlocal_1X_unfoldX_optionXonCreate_selectXmX_rangeXlocal_1_2X_unfoldX_optionXonMatch_selectXmX_tailXlocalX_unfoldX_to_create": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.AddV("person").Property("name", "marko").Property("age", 29)}, func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.Inject(map[interface{}]interface [...]
"g_mergeVXlabel_ab_name_markoX_multilabel_create": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.MergeV(map[interface{}]interface{}{gremlingo.T.Label: []interface{}{"person", "employee"}, "name": "marko" })}, func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.V()}, func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.V().HasLabel [...]
"g_mergeVXlabel_abc_name_testX_multilabel_create": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.MergeV(map[interface{}]interface{}{gremlingo.T.Label: []interface{}{"a", "b", "c"}, "name": "test" })}, func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.V()}, func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.V().HasLabel("a").Ha [...]
- "g_mergeVXlabel_person_name_markoX_single_label": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.MergeV(map[interface{}]interface{}{gremlingo.T.Label: "person", "name": "marko" })}, func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.V()}, func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.V().HasLabel("person")}, func(g *gremlin [...]
"g_mergeVXlabel_ab_name_markoX_multilabel_match": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.AddV("person").AddLabel("employee").Property("name", "marko")}, func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.MergeV(map[interface{}]interface{}{gremlingo.T.Label: []interface{}{"person", "employee"}, "name": "marko" })}, func(g *gremlingo.GraphTraversalSource, p map[string]inte [...]
"g_mergeVXlabel_ab_name_markoX_multilabel_nomatch": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.AddV("person").Property("name", "marko")}, func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.MergeV(map[interface{}]interface{}{gremlingo.T.Label: []interface{}{"person", "employee"}, "name": "marko" })}, func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo [...]
"g_mergeVXlabel_person_name_markoX_optionXonMatch_label_managerX": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.AddV("person").AddLabel("employee").Property("name", "marko")}, func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.MergeV(map[interface{}]interface{}{gremlingo.T.Label: "person", "name": "marko" }).Option(gremlingo.Merge.OnMatch, map[interface{}]interface{}{gremlingo [...]
"g_mergeVXlabel_person_name_markoX_optionXonMatch_label_manager_directorX": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.AddV("person").Property("name", "marko")}, func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.MergeV(map[interface{}]interface{}{gremlingo.T.Label: "person", "name": "marko" }).Option(gremlingo.Merge.OnMatch, map[interface{}]interface{}{gremlingo.T.Label: [] [...]
"g_mergeVXlabel_person_name_markoX_optionXonMatch_label_emptyX": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.AddV("person").Property("name", "marko")}, func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.MergeV(map[interface{}]interface{}{gremlingo.T.Label: "person", "name": "marko" }).Option(gremlingo.Merge.OnMatch, map[interface{}]interface{}{gremlingo.T.Label: []interface{} [...]
+ "g_mergeVXname_markoX_optionXonCreate_label_ab_name_markoX": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.MergeV(map[interface{}]interface{}{"name": "marko" }).Option(gremlingo.Merge.OnCreate, map[interface{}]interface{}{gremlingo.T.Label: []interface{}{"person", "employee"}, "name": "marko" })}, func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.V()}, func(g *gremlingo.GraphT [...]
+ "g_mergeVXlabel_person_name_markoX_optionXonMatch_label_existingX": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.AddV("person").AddLabel("employee").Property("name", "marko")}, func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.MergeV(map[interface{}]interface{}{gremlingo.T.Label: "person", "name": "marko" }).Option(gremlingo.Merge.OnMatch, map[interface{}]interface{}{gremling [...]
"g_V_age_min": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.V().Values("age").Min()}},
"g_V_foo_min": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.V().Values("foo").Min()}},
"g_V_name_min": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.V().Values("name").Min()}},
@@ -2053,6 +2053,7 @@ var translationMap = map[string][]func(g *gremlingo.GraphTraversalSource, p map[
"g_V_dropLabels_defaultLabel": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.AddV("person")}, func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.V().DropLabels().Labels()}},
"g_E_dropLabelXknowsX_labels": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.AddV("person").As("a").AddV("person").As("b").AddE("knows").From("a").To("b")}, func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.E().DropLabel("knows").Labels().Fold()}},
"g_E_dropLabels_labels": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.AddV("person").As("a").AddV("person").As("b").AddE("knows").From("a").To("b")}, func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.E().DropLabels().Labels()}},
+ "g_V_dropLabelXnonExistentX_labels": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.AddV("a", "b")}, func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.V().DropLabel("xyz").Labels()}},
"g_V_fail": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.V().Fail()}},
"g_V_failXmsgX": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.V().Fail("msg")}},
"g_V_unionXout_failX": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.V().Union(gremlingo.T__.Out(), gremlingo.T__.Fail())}},
diff --git a/gremlin-js/gremlin-javascript/test/cucumber/feature-steps.js b/gremlin-js/gremlin-javascript/test/cucumber/feature-steps.js
index bb956a2538..66e002aaf6 100644
--- a/gremlin-js/gremlin-javascript/test/cucumber/feature-steps.js
+++ b/gremlin-js/gremlin-javascript/test/cucumber/feature-steps.js
@@ -111,7 +111,13 @@ Given(/^the (.+) graph$/, function (graphName) {
if (ignoredScenarios[this.scenario]) {
return 'skipped';
}
- this.graphName = graphName;
+
+ // Multi-label tests use the gmultilabel traversal source for empty graphs
+ if (this.isMultiLabel && graphName === 'empty') {
+ this.graphName = 'multilabel';
+ } else {
+ this.graphName = graphName;
+ }
const data = this.getData();
this.g = anon.traversal().with_(data.connection);
@@ -119,9 +125,12 @@ Given(/^the (.+) graph$/, function (graphName) {
this.g = this.g.withComputer();
}
- if (graphName === 'empty') {
+ if (this.graphName === 'empty') {
return this.cleanEmptyGraph();
}
+ if (this.graphName === 'multilabel') {
+ return this.cleanMultilabelGraph();
+ }
});
Given('the graph initializer of', function (traversalText) {
@@ -151,6 +160,8 @@ Given(/^using the parameter (.+) defined as "(.+)"$/, function (paramName, strin
let p = Promise.resolve();
if (this.graphName === 'empty') {
p = this.loadEmptyGraphData();
+ } else if (this.graphName === 'multilabel') {
+ p = this.loadMultilabelGraphData();
}
return p.then(() => {
this.parameters[paramName] = parseValue.call(this, stringValue);
@@ -168,6 +179,8 @@ Given(/^using the side effect (.+) defined as "(.+)"$/, function (sideEffectKey,
let p = Promise.resolve();
if (this.graphName === 'empty') {
p = this.loadEmptyGraphData();
+ } else if (this.graphName === 'multilabel') {
+ p = this.loadMultilabelGraphData();
}
return p.then(() => {
this.sideEffects[sideEffectKey] = parseValue.call(this, stringValue);
diff --git a/gremlin-js/gremlin-javascript/test/cucumber/gremlin.js b/gremlin-js/gremlin-javascript/test/cucumber/gremlin.js
index fed99737ac..97df92ce24 100644
--- a/gremlin-js/gremlin-javascript/test/cucumber/gremlin.js
+++ b/gremlin-js/gremlin-javascript/test/cucumber/gremlin.js
@@ -1254,7 +1254,6 @@ const gremlins = {
g_V_valuesXnameX_lTrim: [function({g}) { return g.addV("person").property("name", " marko ").property("age", 29).as("marko").addV("person").property("name", " vadas ").property("age", 27).as("vadas").addV("software").property("name", " lop").property("lang", "java").as("lop").addV("person").property("name", "josh ").property("age", 32).as("josh").addV("software").property("name", " ripple ").property("lang", "java").as("ripple").addV("person").property("name", "peter").proper [...]
g_V_valuesXnameX_order_fold_lTrimXlocalX: [function({g}) { return g.addV("person").property("name", " marko ").property("age", 29).as("marko").addV("person").property("name", " vadas ").property("age", 27).as("vadas").addV("software").property("name", " lop").property("lang", "java").as("lop").addV("person").property("name", "josh ").property("age", 32).as("josh").addV("software").property("name", " ripple ").property("lang", "java").as("ripple").addV("person").property("name [...]
g_V_hasLabelXpersonX_labels: [function({g}) { return g.V().hasLabel("person").labels() }],
- g_addVXa_bX_labels_fold: [function({g}) { return g.addV("a", "b") }, function({g}) { return g.V().labels().fold() }],
g_addVXa_bX_labels_count: [function({g}) { return g.addV("a", "b") }, function({g}) { return g.V().labels().count() }],
g_addV_labels: [function({g}) { return g.addV() }, function({g}) { return g.V().labels() }],
g_E_labels: [function({g}) { return g.E().hasLabel("knows").labels() }],
@@ -1526,12 +1525,13 @@ const gremlins = {
g_injectXlist1_list2_list3X_fold_asXmX_mergeVXselectXmX_limitXlocal_1X_unfoldX_optionXonCreate_selectXmX_rangeXlocal_1_2X_unfoldX_optionXonMatch_selectXmX_tailXlocalX_unfoldX_to_create: [function({g}) { return g.addV("person").property("name", "marko").property("age", 29) }, function({g}) { return g.inject(new Map([[T.label, "person"], ["name", "stephen"]]), new Map([[T.label, "person"], ["name", "stephen"]]), new Map([["created", "N"]])).fold().as("m").mergeV(__.select("m").limit(Sc [...]
g_mergeVXlabel_ab_name_markoX_multilabel_create: [function({g}) { return g.mergeV(new Map([[T.label, ["person", "employee"]], ["name", "marko"]])) }, function({g}) { return g.V() }, function({g}) { return g.V().hasLabel("person").hasLabel("employee") }, function({g}) { return g.V().has("name", "marko") }],
g_mergeVXlabel_abc_name_testX_multilabel_create: [function({g}) { return g.mergeV(new Map([[T.label, ["a", "b", "c"]], ["name", "test"]])) }, function({g}) { return g.V() }, function({g}) { return g.V().hasLabel("a").hasLabel("b").hasLabel("c") }],
- g_mergeVXlabel_person_name_markoX_single_label: [function({g}) { return g.mergeV(new Map([[T.label, "person"], ["name", "marko"]])) }, function({g}) { return g.V() }, function({g}) { return g.V().hasLabel("person") }, function({g}) { return g.V().has("name", "marko") }],
g_mergeVXlabel_ab_name_markoX_multilabel_match: [function({g}) { return g.addV("person").addLabel("employee").property("name", "marko") }, function({g}) { return g.mergeV(new Map([[T.label, ["person", "employee"]], ["name", "marko"]])) }, function({g}) { return g.V() }, function({g}) { return g.V().hasLabel("person").hasLabel("employee") }],
g_mergeVXlabel_ab_name_markoX_multilabel_nomatch: [function({g}) { return g.addV("person").property("name", "marko") }, function({g}) { return g.mergeV(new Map([[T.label, ["person", "employee"]], ["name", "marko"]])) }, function({g}) { return g.V() }],
g_mergeVXlabel_person_name_markoX_optionXonMatch_label_managerX: [function({g}) { return g.addV("person").addLabel("employee").property("name", "marko") }, function({g}) { return g.mergeV(new Map([[T.label, "person"], ["name", "marko"]])).option(Merge.onMatch, new Map([[T.label, "manager"]])) }, function({g}) { return g.V() }, function({g}) { return g.V().hasLabel("manager") }, function({g}) { return g.V().hasLabel("person") }, function({g}) { return g.V().hasLabel("employee") }],
g_mergeVXlabel_person_name_markoX_optionXonMatch_label_manager_directorX: [function({g}) { return g.addV("person").property("name", "marko") }, function({g}) { return g.mergeV(new Map([[T.label, "person"], ["name", "marko"]])).option(Merge.onMatch, new Map([[T.label, ["manager", "director"]]])) }, function({g}) { return g.V() }, function({g}) { return g.V().hasLabel("manager").hasLabel("director") }, function({g}) { return g.V().hasLabel("person") }],
g_mergeVXlabel_person_name_markoX_optionXonMatch_label_emptyX: [function({g}) { return g.addV("person").property("name", "marko") }, function({g}) { return g.mergeV(new Map([[T.label, "person"], ["name", "marko"]])).option(Merge.onMatch, new Map([[T.label, []]])) }, function({g}) { return g.V() }, function({g}) { return g.V().hasLabel("person") }],
+ g_mergeVXname_markoX_optionXonCreate_label_ab_name_markoX: [function({g}) { return g.mergeV(new Map([["name", "marko"]])).option(Merge.onCreate, new Map([[T.label, ["person", "employee"]], ["name", "marko"]])) }, function({g}) { return g.V() }, function({g}) { return g.V().hasLabel("person").hasLabel("employee") }, function({g}) { return g.V().has("name", "marko") }],
+ g_mergeVXlabel_person_name_markoX_optionXonMatch_label_existingX: [function({g}) { return g.addV("person").addLabel("employee").property("name", "marko") }, function({g}) { return g.mergeV(new Map([[T.label, "person"], ["name", "marko"]])).option(Merge.onMatch, new Map([[T.label, "person"]])) }, function({g}) { return g.V() }, function({g}) { return g.V().hasLabel("person").hasLabel("employee") }],
g_V_age_min: [function({g}) { return g.V().values("age").min() }],
g_V_foo_min: [function({g}) { return g.V().values("foo").min() }],
g_V_name_min: [function({g}) { return g.V().values("name").min() }],
@@ -2084,6 +2084,7 @@ const gremlins = {
g_V_dropLabels_defaultLabel: [function({g}) { return g.addV("person") }, function({g}) { return g.V().dropLabels().labels() }],
g_E_dropLabelXknowsX_labels: [function({g}) { return g.addV("person").as("a").addV("person").as("b").addE("knows").from_("a").to("b") }, function({g}) { return g.E().dropLabel("knows").labels().fold() }],
g_E_dropLabels_labels: [function({g}) { return g.addV("person").as("a").addV("person").as("b").addE("knows").from_("a").to("b") }, function({g}) { return g.E().dropLabels().labels() }],
+ g_V_dropLabelXnonExistentX_labels: [function({g}) { return g.addV("a", "b") }, function({g}) { return g.V().dropLabel("xyz").labels() }],
g_V_fail: [function({g}) { return g.V().fail() }],
g_V_failXmsgX: [function({g}) { return g.V().fail("msg") }],
g_V_unionXout_failX: [function({g}) { return g.V().union(__.out(), __.fail()) }],
diff --git a/gremlin-js/gremlin-javascript/test/cucumber/world.js b/gremlin-js/gremlin-javascript/test/cucumber/world.js
index 8dcd7d18ba..fd8e21449f 100644
--- a/gremlin-js/gremlin-javascript/test/cucumber/world.js
+++ b/gremlin-js/gremlin-javascript/test/cucumber/world.js
@@ -54,6 +54,12 @@ TinkerPopWorld.prototype.cleanEmptyGraph = function () {
return g.V().drop().toList();
};
+TinkerPopWorld.prototype.cleanMultilabelGraph = function () {
+ const connection = this.cache['multilabel'].connection;
+ const g = anon.traversal().withRemote(connection);
+ return g.V().drop().toList();
+};
+
TinkerPopWorld.prototype.loadEmptyGraphData = function () {
const cacheData = this.cache['empty'];
const c = cacheData.connection;
@@ -64,16 +70,30 @@ TinkerPopWorld.prototype.loadEmptyGraphData = function () {
});
};
+TinkerPopWorld.prototype.loadMultilabelGraphData = function () {
+ const cacheData = this.cache['multilabel'];
+ const c = cacheData.connection;
+ return Promise.all([ getVertices(c), getEdges(c), getVertexProperties(c) ]).then(values => {
+ cacheData.vertices = values[0];
+ cacheData.edges = values[1];
+ cacheData.vertexProperties = values[2]
+ });
+};
+
setWorldConstructor(TinkerPopWorld);
BeforeAll(function () {
// load all traversals
- const promises = ['modern', 'classic', 'crew', 'grateful', 'sink', 'empty'].map(graphName => {
+ const promises = ['modern', 'classic', 'crew', 'grateful', 'sink', 'empty', 'multilabel'].map(graphName => {
let connection = null;
if (graphName === 'empty') {
connection = getConnection('ggraph');
return connection.open().then(() => cache['empty'] = { connection: connection });
}
+ if (graphName === 'multilabel') {
+ connection = getConnection('gmultilabel');
+ return connection.open().then(() => cache['multilabel'] = { connection: connection });
+ }
connection = getConnection('g' + graphName);
return connection.open()
.then(() => Promise.all([getVertices(connection), getEdges(connection), getVertexProperties(connection)]))
@@ -96,6 +116,7 @@ AfterAll(function () {
Before(function (info) {
this.scenario = info.pickle.name;
this.cache = cache;
+ this.isMultiLabel = info.pickle.tags && info.pickle.tags.some(t => t.name === '@MultiLabel');
});
Before({tags: "@GraphComputerOnly"}, function() {
@@ -118,10 +139,6 @@ Before({tags: "@DataDuration"}, function() {
return 'skipped'
})
-Before({tags: "@MultiLabel"}, function() {
- return 'skipped'
-})
-
function getVertices(connection) {
const g = anon.traversal().withRemote(connection);
return g.V().group().by('name').by(__.tail()).next().then(it => {
diff --git a/gremlin-python/src/main/python/tests/feature/feature_steps.py b/gremlin-python/src/main/python/tests/feature/feature_steps.py
index 56feab3a29..d3529dc46d 100644
--- a/gremlin-python/src/main/python/tests/feature/feature_steps.py
+++ b/gremlin-python/src/main/python/tests/feature/feature_steps.py
@@ -90,15 +90,17 @@ def choose_graph(step, graph_name):
if not step.context.ignore:
step.context.ignore = "WithReservedKeysVerificationStrategy" in tagset
- # Multi-label steps not yet available in Python GLV
- if not step.context.ignore:
- step.context.ignore = "MultiLabel" in tagset
-
if (step.context.ignore):
return
- step.context.graph_name = graph_name
- step.context.g = traversal().with_(step.context.remote_conn[graph_name]).with_('language', 'gremlin-lang')
+ # Multi-label tests use the gmultilabel traversal source for empty graphs
+ is_multilabel = "MultiLabel" in tagset
+ if is_multilabel and graph_name == "empty":
+ step.context.graph_name = "multilabel"
+ step.context.g = traversal().with_(step.context.remote_conn["multilabel"]).with_('language', 'gremlin-lang')
+ else:
+ step.context.graph_name = graph_name
+ step.context.g = traversal().with_(step.context.remote_conn[graph_name]).with_('language', 'gremlin-lang')
@given("the graph initializer of")
@@ -459,6 +461,13 @@ def __find_cached_element(ctx, graph_name, identifier, element_type):
cache = world.create_lookup_vp(ctx.remote_conn["empty"])
else:
cache = world.create_lookup_e(ctx.remote_conn["empty"])
+ elif graph_name == "multilabel":
+ if element_type == "v":
+ cache = world.create_lookup_v(ctx.remote_conn["multilabel"])
+ elif element_type == "vp":
+ cache = world.create_lookup_vp(ctx.remote_conn["multilabel"])
+ else:
+ cache = world.create_lookup_e(ctx.remote_conn["multilabel"])
else:
if element_type == "v":
cache = ctx.lookup_v[graph_name]
diff --git a/gremlin-python/src/main/python/tests/feature/gremlin.py b/gremlin-python/src/main/python/tests/feature/gremlin.py
index 5c7cbe05be..ba27449594 100644
--- a/gremlin-python/src/main/python/tests/feature/gremlin.py
+++ b/gremlin-python/src/main/python/tests/feature/gremlin.py
@@ -1228,7 +1228,6 @@ world.gremlins = {
'g_V_valuesXnameX_lTrim': [(lambda g:g.add_v('person').property('name', ' marko ').property('age', 29).as_('marko').add_v('person').property('name', ' vadas ').property('age', 27).as_('vadas').add_v('software').property('name', ' lop').property('lang', 'java').as_('lop').add_v('person').property('name', 'josh ').property('age', 32).as_('josh').add_v('software').property('name', ' ripple ').property('lang', 'java').as_('ripple').add_v('person').property('name', 'peter').proper [...]
'g_V_valuesXnameX_order_fold_lTrimXlocalX': [(lambda g:g.add_v('person').property('name', ' marko ').property('age', 29).as_('marko').add_v('person').property('name', ' vadas ').property('age', 27).as_('vadas').add_v('software').property('name', ' lop').property('lang', 'java').as_('lop').add_v('person').property('name', 'josh ').property('age', 32).as_('josh').add_v('software').property('name', ' ripple ').property('lang', 'java').as_('ripple').add_v('person').property('name [...]
'g_V_hasLabelXpersonX_labels': [(lambda g:g.V().has_label('person').labels())],
- 'g_addVXa_bX_labels_fold': [(lambda g:g.add_v('a', 'b')), (lambda g:g.V().labels().fold())],
'g_addVXa_bX_labels_count': [(lambda g:g.add_v('a', 'b')), (lambda g:g.V().labels().count())],
'g_addV_labels': [(lambda g:g.add_v()), (lambda g:g.V().labels())],
'g_E_labels': [(lambda g:g.E().has_label('knows').labels())],
@@ -1500,12 +1499,13 @@ world.gremlins = {
'g_injectXlist1_list2_list3X_fold_asXmX_mergeVXselectXmX_limitXlocal_1X_unfoldX_optionXonCreate_selectXmX_rangeXlocal_1_2X_unfoldX_optionXonMatch_selectXmX_tailXlocalX_unfoldX_to_create': [(lambda g:g.add_v('person').property('name', 'marko').property('age', 29)), (lambda g:g.inject({ T.label: 'person', 'name': 'stephen' }, { T.label: 'person', 'name': 'stephen' }, { 'created': 'N' }).fold().as_('m').merge_v(__.select('m').limit(Scope.local, 1).unfold()).option(Merge.on_create, __.se [...]
'g_mergeVXlabel_ab_name_markoX_multilabel_create': [(lambda g:g.merge_v({ T.label: ['person', 'employee'], 'name': 'marko' })), (lambda g:g.V()), (lambda g:g.V().has_label('person').has_label('employee')), (lambda g:g.V().has('name', 'marko'))],
'g_mergeVXlabel_abc_name_testX_multilabel_create': [(lambda g:g.merge_v({ T.label: ['a', 'b', 'c'], 'name': 'test' })), (lambda g:g.V()), (lambda g:g.V().has_label('a').has_label('b').has_label('c'))],
- 'g_mergeVXlabel_person_name_markoX_single_label': [(lambda g:g.merge_v({ T.label: 'person', 'name': 'marko' })), (lambda g:g.V()), (lambda g:g.V().has_label('person')), (lambda g:g.V().has('name', 'marko'))],
'g_mergeVXlabel_ab_name_markoX_multilabel_match': [(lambda g:g.add_v('person').add_label('employee').property('name', 'marko')), (lambda g:g.merge_v({ T.label: ['person', 'employee'], 'name': 'marko' })), (lambda g:g.V()), (lambda g:g.V().has_label('person').has_label('employee'))],
'g_mergeVXlabel_ab_name_markoX_multilabel_nomatch': [(lambda g:g.add_v('person').property('name', 'marko')), (lambda g:g.merge_v({ T.label: ['person', 'employee'], 'name': 'marko' })), (lambda g:g.V())],
'g_mergeVXlabel_person_name_markoX_optionXonMatch_label_managerX': [(lambda g:g.add_v('person').add_label('employee').property('name', 'marko')), (lambda g:g.merge_v({ T.label: 'person', 'name': 'marko' }).option(Merge.on_match, { T.label: 'manager' })), (lambda g:g.V()), (lambda g:g.V().has_label('manager')), (lambda g:g.V().has_label('person')), (lambda g:g.V().has_label('employee'))],
'g_mergeVXlabel_person_name_markoX_optionXonMatch_label_manager_directorX': [(lambda g:g.add_v('person').property('name', 'marko')), (lambda g:g.merge_v({ T.label: 'person', 'name': 'marko' }).option(Merge.on_match, { T.label: ['manager', 'director'] })), (lambda g:g.V()), (lambda g:g.V().has_label('manager').has_label('director')), (lambda g:g.V().has_label('person'))],
'g_mergeVXlabel_person_name_markoX_optionXonMatch_label_emptyX': [(lambda g:g.add_v('person').property('name', 'marko')), (lambda g:g.merge_v({ T.label: 'person', 'name': 'marko' }).option(Merge.on_match, { T.label: [] })), (lambda g:g.V()), (lambda g:g.V().has_label('person'))],
+ 'g_mergeVXname_markoX_optionXonCreate_label_ab_name_markoX': [(lambda g:g.merge_v({ 'name': 'marko' }).option(Merge.on_create, { T.label: ['person', 'employee'], 'name': 'marko' })), (lambda g:g.V()), (lambda g:g.V().has_label('person').has_label('employee')), (lambda g:g.V().has('name', 'marko'))],
+ 'g_mergeVXlabel_person_name_markoX_optionXonMatch_label_existingX': [(lambda g:g.add_v('person').add_label('employee').property('name', 'marko')), (lambda g:g.merge_v({ T.label: 'person', 'name': 'marko' }).option(Merge.on_match, { T.label: 'person' })), (lambda g:g.V()), (lambda g:g.V().has_label('person').has_label('employee'))],
'g_V_age_min': [(lambda g:g.V().values('age').min_())],
'g_V_foo_min': [(lambda g:g.V().values('foo').min_())],
'g_V_name_min': [(lambda g:g.V().values('name').min_())],
@@ -2058,6 +2058,7 @@ world.gremlins = {
'g_V_dropLabels_defaultLabel': [(lambda g:g.add_v('person')), (lambda g:g.V().drop_labels().labels())],
'g_E_dropLabelXknowsX_labels': [(lambda g:g.add_v('person').as_('a').add_v('person').as_('b').add_e('knows').from_('a').to('b')), (lambda g:g.E().drop_label('knows').labels().fold())],
'g_E_dropLabels_labels': [(lambda g:g.add_v('person').as_('a').add_v('person').as_('b').add_e('knows').from_('a').to('b')), (lambda g:g.E().drop_labels().labels())],
+ 'g_V_dropLabelXnonExistentX_labels': [(lambda g:g.add_v('a', 'b')), (lambda g:g.V().drop_label('xyz').labels())],
'g_V_fail': [(lambda g:g.V().fail())],
'g_V_failXmsgX': [(lambda g:g.V().fail('msg'))],
'g_V_unionXout_failX': [(lambda g:g.V().union(__.out(), __.fail()))],
diff --git a/gremlin-python/src/main/python/tests/feature/terrain.py b/gremlin-python/src/main/python/tests/feature/terrain.py
index 781216bb63..b1b5a0ef92 100644
--- a/gremlin-python/src/main/python/tests/feature/terrain.py
+++ b/gremlin-python/src/main/python/tests/feature/terrain.py
@@ -83,10 +83,20 @@ def prepare_traversal_source(scenario):
g = traversal().with_(remote)
g.V().drop().iterate()
+ # create a fresh remote for multi-label tests that need ZERO_OR_MORE vertex label cardinality
+ tagset = [tag.name for tag in scenario.all_tags]
+ if "MultiLabel" in tagset:
+ multilabel_remote = __create_remote("gmultilabel")
+ scenario.context.remote_conn["multilabel"] = multilabel_remote
+ gml = traversal().with_(multilabel_remote)
+ gml.V().drop().iterate()
+
@after.each_scenario
def close_traversal_source(scenario):
scenario.context.remote_conn["empty"].close()
+ if "multilabel" in scenario.context.remote_conn:
+ scenario.context.remote_conn["multilabel"].close()
@after.all
diff --git a/gremlin-server/conf/tinkergraph-multilabel.properties b/gremlin-server/conf/tinkergraph-multilabel.properties
new file mode 100644
index 0000000000..54391e8c5f
--- /dev/null
+++ b/gremlin-server/conf/tinkergraph-multilabel.properties
@@ -0,0 +1,21 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+gremlin.graph=org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph
+gremlin.tinkergraph.vertexIdManager=INTEGER
+gremlin.tinkergraph.edgeIdManager=INTEGER
+gremlin.tinkergraph.vertexPropertyIdManager=LONG
+gremlin.tinkergraph.vertexLabelCardinality=ZERO_OR_MORE
diff --git a/gremlin-server/src/test/java/org/apache/tinkerpop/gremlin/driver/remote/RemoteWorld.java b/gremlin-server/src/test/java/org/apache/tinkerpop/gremlin/driver/remote/RemoteWorld.java
index 54b811d6e4..dbf51c79d7 100644
--- a/gremlin-server/src/test/java/org/apache/tinkerpop/gremlin/driver/remote/RemoteWorld.java
+++ b/gremlin-server/src/test/java/org/apache/tinkerpop/gremlin/driver/remote/RemoteWorld.java
@@ -23,6 +23,7 @@ import org.apache.tinkerpop.gremlin.LoadGraphWith;
import org.apache.tinkerpop.gremlin.TestHelper;
import org.apache.tinkerpop.gremlin.driver.Client;
import org.apache.tinkerpop.gremlin.driver.Cluster;
+import org.apache.tinkerpop.gremlin.driver.RequestOptions;
import org.apache.tinkerpop.gremlin.features.World;
import org.apache.tinkerpop.gremlin.process.computer.Computer;
import org.apache.tinkerpop.gremlin.process.traversal.AnonymousTraversalSource;
@@ -99,6 +100,18 @@ public abstract class RemoteWorld implements World {
return AnonymousTraversalSource.traversal().withRemote(DriverRemoteConnection.using(client, remoteTraversalSource));
}
+ @Override
+ public GraphTraversalSource getMultiLabelGraphTraversalSource() {
+ final Client client = cluster.connect();
+ try { // Clear data before run because tests are allowed to modify data for the multi-label graph.
+ final RequestOptions options = RequestOptions.build().addG("gmultilabel").create();
+ client.submit("g.V().drop()", options).all().get();
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ return AnonymousTraversalSource.traversal().withRemote(DriverRemoteConnection.using(client, "gmultilabel"));
+ }
+
@Override
public String changePathToDataFile(final String pathToFileFromGremlin) {
return ".." + File.separator + pathToFileFromGremlin;
@@ -137,6 +150,11 @@ public abstract class RemoteWorld implements World {
}
}
+ @Override
+ public GraphTraversalSource getMultiLabelGraphTraversalSource() {
+ throw new AssumptionViolatedException("GraphComputer does not support mutation");
+ }
+
@Override
public void beforeEachScenario(Scenario scenario) {
super.beforeEachScenario(scenario);
diff --git a/gremlin-server/src/test/java/org/apache/tinkerpop/gremlin/server/util/CheckedGraphManagerTest.java b/gremlin-server/src/test/java/org/apache/tinkerpop/gremlin/server/util/CheckedGraphManagerTest.java
index 9fed97cf98..490ead1423 100644
--- a/gremlin-server/src/test/java/org/apache/tinkerpop/gremlin/server/util/CheckedGraphManagerTest.java
+++ b/gremlin-server/src/test/java/org/apache/tinkerpop/gremlin/server/util/CheckedGraphManagerTest.java
@@ -66,7 +66,7 @@ public class CheckedGraphManagerTest {
public void justAGraphFails() {
settings.graphs.put("invalid", "conf/invalidPath");
final GraphManager manager = new CheckedGraphManager(settings);
- assertThat(manager.getGraphNames(), hasSize(7));
+ assertThat(manager.getGraphNames(), hasSize(8));
}
/**
diff --git a/gremlin-server/src/test/java/org/apache/tinkerpop/gremlin/server/util/DefaultGraphManagerTest.java b/gremlin-server/src/test/java/org/apache/tinkerpop/gremlin/server/util/DefaultGraphManagerTest.java
index 6cb6238a89..87af675779 100644
--- a/gremlin-server/src/test/java/org/apache/tinkerpop/gremlin/server/util/DefaultGraphManagerTest.java
+++ b/gremlin-server/src/test/java/org/apache/tinkerpop/gremlin/server/util/DefaultGraphManagerTest.java
@@ -48,7 +48,7 @@ public class DefaultGraphManagerTest {
final Set<String> graphNames = graphManager.getGraphNames();
assertNotNull(graphNames);
- assertEquals(7, graphNames.size());
+ assertEquals(8, graphNames.size());
assertThat(graphNames.contains("graph"), is(true));
assertThat(graphNames.contains("classic"), is(true));
@@ -68,7 +68,7 @@ public class DefaultGraphManagerTest {
final Bindings bindings = graphManager.getAsBindings();
assertNotNull(bindings);
- assertEquals(7, bindings.size());
+ assertEquals(8, bindings.size());
assertThat(bindings.containsKey("graph"), is(true));
assertThat(bindings.containsKey("classic"), is(true));
assertThat(bindings.containsKey("modern"), is(true));
@@ -99,7 +99,7 @@ public class DefaultGraphManagerTest {
final Set<String> graphNames = graphManager.getGraphNames();
assertNotNull(graphNames);
- assertEquals(8, graphNames.size());
+ assertEquals(9, graphNames.size());
assertThat(graphNames.contains("newGraph"), is(true));
assertThat(graphNames.contains("graph"), is(true));
assertThat(graphNames.contains("classic"), is(true));
@@ -120,14 +120,14 @@ public class DefaultGraphManagerTest {
graphManager.putGraph("newGraph", graph);
final Set<String> graphNames = graphManager.getGraphNames();
assertNotNull(graphNames);
- assertEquals(8, graphNames.size());
+ assertEquals(9, graphNames.size());
assertThat(graphNames.contains("newGraph"), is(true));
assertThat(graphManager.getGraph("newGraph"), instanceOf(TinkerGraph.class));
graphManager.removeGraph("newGraph");
final Set<String> graphNames2 = graphManager.getGraphNames();
- assertEquals(7, graphNames2.size());
+ assertEquals(8, graphNames2.size());
assertThat(graphNames2.contains("newGraph"), is(false));
}
diff --git a/gremlin-server/src/test/resources/org/apache/tinkerpop/gremlin/server/gremlin-server-integration.yaml b/gremlin-server/src/test/resources/org/apache/tinkerpop/gremlin/server/gremlin-server-integration.yaml
index be135f03c7..5e9a753eed 100644
--- a/gremlin-server/src/test/resources/org/apache/tinkerpop/gremlin/server/gremlin-server-integration.yaml
+++ b/gremlin-server/src/test/resources/org/apache/tinkerpop/gremlin/server/gremlin-server-integration.yaml
@@ -35,6 +35,9 @@ graphs: {
graph: {
configuration: conf/tinkergraph-empty.properties,
traversalSources: [{name: g}, {name: ggraph}]},
+ multilabel: {
+ configuration: conf/tinkergraph-multilabel.properties,
+ traversalSources: [{name: gmultilabel}]},
classic: {
configuration: conf/tinkergraph-empty.properties,
traversalSources: [{name: gclassic}]},
diff --git a/gremlin-server/src/test/scripts/tinkergraph-multilabel.properties b/gremlin-server/src/test/scripts/tinkergraph-multilabel.properties
new file mode 100644
index 0000000000..54391e8c5f
--- /dev/null
+++ b/gremlin-server/src/test/scripts/tinkergraph-multilabel.properties
@@ -0,0 +1,21 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+gremlin.graph=org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph
+gremlin.tinkergraph.vertexIdManager=INTEGER
+gremlin.tinkergraph.edgeIdManager=INTEGER
+gremlin.tinkergraph.vertexPropertyIdManager=LONG
+gremlin.tinkergraph.vertexLabelCardinality=ZERO_OR_MORE
diff --git a/gremlin-test/src/main/java/org/apache/tinkerpop/gremlin/features/StepDefinition.java b/gremlin-test/src/main/java/org/apache/tinkerpop/gremlin/features/StepDefinition.java
index 59bc869f63..cf47147416 100644
--- a/gremlin-test/src/main/java/org/apache/tinkerpop/gremlin/features/StepDefinition.java
+++ b/gremlin-test/src/main/java/org/apache/tinkerpop/gremlin/features/StepDefinition.java
@@ -111,6 +111,7 @@ public final class StepDefinition {
private static final ObjectMapper mapper = new ObjectMapper();
private World world;
+ private Scenario currentScenario;
private GraphTraversalSource g;
private File tempWorkingDir;
private final Map<String, Object> stringParameters = new HashMap<>();
@@ -316,6 +317,7 @@ public final class StepDefinition {
@Before
public void beforeEachScenario(final Scenario scenario) throws Exception {
+ this.currentScenario = scenario;
world.beforeEachScenario(scenario);
stringParameters.clear();
if (traversal != null) {
@@ -355,10 +357,16 @@ public final class StepDefinition {
@Given("the {word} graph")
public void givenTheXGraph(final String graphName) {
- if (graphName.equals("empty"))
- this.g = world.getGraphTraversalSource(null);
- else
+ final boolean isMultiLabel = currentScenario != null &&
+ currentScenario.getSourceTagNames().contains("@MultiLabel");
+ if (graphName.equals("empty")) {
+ if (isMultiLabel)
+ this.g = world.getMultiLabelGraphTraversalSource();
+ else
+ this.g = world.getGraphTraversalSource(null);
+ } else {
this.g = world.getGraphTraversalSource(GraphData.valueOf(graphName.toUpperCase()));
+ }
}
@Given("the graph initializer of")
diff --git a/gremlin-test/src/main/java/org/apache/tinkerpop/gremlin/features/World.java b/gremlin-test/src/main/java/org/apache/tinkerpop/gremlin/features/World.java
index b5e284250c..cd65867f16 100644
--- a/gremlin-test/src/main/java/org/apache/tinkerpop/gremlin/features/World.java
+++ b/gremlin-test/src/main/java/org/apache/tinkerpop/gremlin/features/World.java
@@ -55,6 +55,18 @@ public interface World {
*/
public GraphTraversalSource getGraphTraversalSource(final GraphData graphData);
+ /**
+ * Gets a {@link GraphTraversalSource} configured for multi-label support (ZERO_OR_MORE vertex label cardinality).
+ * This source is used by {@code @MultiLabel} tagged scenarios that require label mutation operations such as
+ * {@code addLabel()} and {@code dropLabel()}. The default implementation delegates to
+ * {@link #getGraphTraversalSource(GraphData)} with {@code null} which works for embedded graphs that already
+ * have multi-label cardinality configured. Remote implementations should override this to connect to a
+ * dedicated multi-label traversal source.
+ */
+ public default GraphTraversalSource getMultiLabelGraphTraversalSource() {
+ return getGraphTraversalSource(null);
+ }
+
/**
* Called before each individual test is executed which provides an opportunity to do some setup. For example,
* if there is a specific test that can't be supported it can be ignored by checking for the name with
diff --git a/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/language/translator/translations.json b/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/language/translator/translations.json
index 86664517ff..0e63097167 100644
--- a/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/language/translator/translations.json
+++ b/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/language/translator/translations.json
@@ -24483,35 +24483,6 @@
}
]
},
- {
- "scenario": "g_addVXa_bX_labels_fold",
- "traversals": [
- {
- "original": "g.addV(\"a\", \"b\")",
- "language": "g.addV(\"a\", \"b\")",
- "canonical": "g.addV(\"a\", \"b\")",
- "anonymized": "g.addV(string0, string1)",
- "dotnet": "g.AddV((string) \"a\", (string) \"b\")",
- "go": "g.AddV(\"a\", \"b\")",
- "groovy": "g.addV(\"a\", \"b\")",
- "java": "g.addV(\"a\", \"b\")",
- "javascript": "g.addV(\"a\", \"b\")",
- "python": "g.add_v('a', 'b')"
- },
- {
- "original": "g.V().labels().fold()",
- "language": "g.V().labels().fold()",
- "canonical": "g.V().labels().fold()",
- "anonymized": "g.V().labels().fold()",
- "dotnet": "g.V().Labels().Fold()",
- "go": "g.V().Labels().Fold()",
- "groovy": "g.V().labels().fold()",
- "java": "g.V().labels().fold()",
- "javascript": "g.V().labels().fold()",
- "python": "g.V().labels().fold()"
- }
- ]
- },
{
"scenario": "g_addVXa_bX_labels_count",
"traversals": [
@@ -32959,59 +32930,6 @@
}
]
},
- {
- "scenario": "g_mergeVXlabel_person_name_markoX_single_label",
- "traversals": [
- {
- "original": "g.mergeV([(T.label): \"person\", name: \"marko\"])",
- "language": "g.mergeV([(T.label):\"person\", name:\"marko\"])",
- "canonical": "g.mergeV([(T.label):\"person\", name:\"marko\"])",
- "anonymized": "g.mergeV(map0)",
- "dotnet": "g.MergeV((IDictionary<object, object>) new Dictionary<object, object> {{ T.Label, \"person\" }, { \"name\", \"marko\" }})",
- "go": "g.MergeV(map[interface{}]interface{}{gremlingo.T.Label: \"person\", \"name\": \"marko\" })",
- "groovy": "g.mergeV([(T.label):\"person\", name:\"marko\"])",
- "java": "g.mergeV(new LinkedHashMap<Object, Object>() {{ put(T.label, \"person\"); put(\"name\", \"marko\"); }})",
- "javascript": "g.mergeV(new Map([[T.label, \"person\"], [\"name\", \"marko\"]]))",
- "python": "g.merge_v({ T.label: 'person', 'name': 'marko' })"
- },
- {
- "original": "g.V()",
- "language": "g.V()",
- "canonical": "g.V()",
- "anonymized": "g.V()",
- "dotnet": "g.V()",
- "go": "g.V()",
- "groovy": "g.V()",
- "java": "g.V()",
- "javascript": "g.V()",
- "python": "g.V()"
- },
- {
- "original": "g.V().hasLabel(\"person\")",
- "language": "g.V().hasLabel(\"person\")",
- "canonical": "g.V().hasLabel(\"person\")",
- "anonymized": "g.V().hasLabel(string0)",
- "dotnet": "g.V().HasLabel(\"person\")",
- "go": "g.V().HasLabel(\"person\")",
- "groovy": "g.V().hasLabel(\"person\")",
- "java": "g.V().hasLabel(\"person\")",
- "javascript": "g.V().hasLabel(\"person\")",
- "python": "g.V().has_label('person')"
- },
- {
- "original": "g.V().has(\"name\",\"marko\")",
- "language": "g.V().has(\"name\", \"marko\")",
- "canonical": "g.V().has(\"name\", \"marko\")",
- "anonymized": "g.V().has(string0, string1)",
- "dotnet": "g.V().Has(\"name\", \"marko\")",
- "go": "g.V().Has(\"name\", \"marko\")",
- "groovy": "g.V().has(\"name\", \"marko\")",
- "java": "g.V().has(\"name\", \"marko\")",
- "javascript": "g.V().has(\"name\", \"marko\")",
- "python": "g.V().has('name', 'marko')"
- }
- ]
- },
{
"scenario": "g_mergeVXlabel_ab_name_markoX_multilabel_match",
"traversals": [
@@ -33301,6 +33219,112 @@
}
]
},
+ {
+ "scenario": "g_mergeVXname_markoX_optionXonCreate_label_ab_name_markoX",
+ "traversals": [
+ {
+ "original": "g.mergeV([name: \"marko\"]).option(Merge.onCreate, [(T.label): [\"person\",\"employee\"], name: \"marko\"])",
+ "language": "g.mergeV([name:\"marko\"]).option(Merge.onCreate, [(T.label):[\"person\", \"employee\"], name:\"marko\"])",
+ "canonical": "g.mergeV([name:\"marko\"]).option(Merge.onCreate, [(T.label):[\"person\", \"employee\"], name:\"marko\"])",
+ "anonymized": "g.mergeV(map0).option(Merge.onCreate, map1)",
+ "dotnet": "g.MergeV((IDictionary<object, object>) new Dictionary<object, object> {{ \"name\", \"marko\" }}).Option(Merge.OnCreate, (IDictionary<object, object>) new Dictionary<object, object> {{ T.Label, new List<object> { \"person\", \"employee\" } }, { \"name\", \"marko\" }})",
+ "go": "g.MergeV(map[interface{}]interface{}{\"name\": \"marko\" }).Option(gremlingo.Merge.OnCreate, map[interface{}]interface{}{gremlingo.T.Label: []interface{}{\"person\", \"employee\"}, \"name\": \"marko\" })",
+ "groovy": "g.mergeV([name:\"marko\"]).option(Merge.onCreate, [(T.label):[\"person\", \"employee\"], name:\"marko\"])",
+ "java": "g.mergeV(new LinkedHashMap<Object, Object>() {{ put(\"name\", \"marko\"); }}).option(Merge.onCreate, new LinkedHashMap<Object, Object>() {{ put(T.label, new ArrayList<Object>() {{ add(\"person\"); add(\"employee\"); }}); put(\"name\", \"marko\"); }})",
+ "javascript": "g.mergeV(new Map([[\"name\", \"marko\"]])).option(Merge.onCreate, new Map([[T.label, [\"person\", \"employee\"]], [\"name\", \"marko\"]]))",
+ "python": "g.merge_v({ 'name': 'marko' }).option(Merge.on_create, { T.label: ['person', 'employee'], 'name': 'marko' })"
+ },
+ {
+ "original": "g.V()",
+ "language": "g.V()",
+ "canonical": "g.V()",
+ "anonymized": "g.V()",
+ "dotnet": "g.V()",
+ "go": "g.V()",
+ "groovy": "g.V()",
+ "java": "g.V()",
+ "javascript": "g.V()",
+ "python": "g.V()"
+ },
+ {
+ "original": "g.V().hasLabel(\"person\").hasLabel(\"employee\")",
+ "language": "g.V().hasLabel(\"person\").hasLabel(\"employee\")",
+ "canonical": "g.V().hasLabel(\"person\").hasLabel(\"employee\")",
+ "anonymized": "g.V().hasLabel(string0).hasLabel(string1)",
+ "dotnet": "g.V().HasLabel(\"person\").HasLabel(\"employee\")",
+ "go": "g.V().HasLabel(\"person\").HasLabel(\"employee\")",
+ "groovy": "g.V().hasLabel(\"person\").hasLabel(\"employee\")",
+ "java": "g.V().hasLabel(\"person\").hasLabel(\"employee\")",
+ "javascript": "g.V().hasLabel(\"person\").hasLabel(\"employee\")",
+ "python": "g.V().has_label('person').has_label('employee')"
+ },
+ {
+ "original": "g.V().has(\"name\",\"marko\")",
+ "language": "g.V().has(\"name\", \"marko\")",
+ "canonical": "g.V().has(\"name\", \"marko\")",
+ "anonymized": "g.V().has(string0, string1)",
+ "dotnet": "g.V().Has(\"name\", \"marko\")",
+ "go": "g.V().Has(\"name\", \"marko\")",
+ "groovy": "g.V().has(\"name\", \"marko\")",
+ "java": "g.V().has(\"name\", \"marko\")",
+ "javascript": "g.V().has(\"name\", \"marko\")",
+ "python": "g.V().has('name', 'marko')"
+ }
+ ]
+ },
+ {
+ "scenario": "g_mergeVXlabel_person_name_markoX_optionXonMatch_label_existingX",
+ "traversals": [
+ {
+ "original": "g.addV(\"person\").addLabel(\"employee\").property(\"name\", \"marko\")",
+ "language": "g.addV(\"person\").addLabel(\"employee\").property(\"name\", \"marko\")",
+ "canonical": "g.addV(\"person\").addLabel(\"employee\").property(\"name\", \"marko\")",
+ "anonymized": "g.addV(string0).addLabel(string1).property(string2, string3)",
+ "dotnet": "g.AddV((string) \"person\").AddLabel(\"employee\").Property(\"name\", \"marko\")",
+ "go": "g.AddV(\"person\").AddLabel(\"employee\").Property(\"name\", \"marko\")",
+ "groovy": "g.addV(\"person\").addLabel(\"employee\").property(\"name\", \"marko\")",
+ "java": "g.addV(\"person\").addLabel(\"employee\").property(\"name\", \"marko\")",
+ "javascript": "g.addV(\"person\").addLabel(\"employee\").property(\"name\", \"marko\")",
+ "python": "g.add_v('person').add_label('employee').property('name', 'marko')"
+ },
+ {
+ "original": "g.mergeV([(T.label): \"person\", name: \"marko\"]).option(Merge.onMatch, [(T.label): \"person\"])",
+ "language": "g.mergeV([(T.label):\"person\", name:\"marko\"]).option(Merge.onMatch, [(T.label):\"person\"])",
+ "canonical": "g.mergeV([(T.label):\"person\", name:\"marko\"]).option(Merge.onMatch, [(T.label):\"person\"])",
+ "anonymized": "g.mergeV(map0).option(Merge.onMatch, map1)",
+ "dotnet": "g.MergeV((IDictionary<object, object>) new Dictionary<object, object> {{ T.Label, \"person\" }, { \"name\", \"marko\" }}).Option(Merge.OnMatch, (IDictionary<object, object>) new Dictionary<object, object> {{ T.Label, \"person\" }})",
+ "go": "g.MergeV(map[interface{}]interface{}{gremlingo.T.Label: \"person\", \"name\": \"marko\" }).Option(gremlingo.Merge.OnMatch, map[interface{}]interface{}{gremlingo.T.Label: \"person\" })",
+ "groovy": "g.mergeV([(T.label):\"person\", name:\"marko\"]).option(Merge.onMatch, [(T.label):\"person\"])",
+ "java": "g.mergeV(new LinkedHashMap<Object, Object>() {{ put(T.label, \"person\"); put(\"name\", \"marko\"); }}).option(Merge.onMatch, new LinkedHashMap<Object, Object>() {{ put(T.label, \"person\"); }})",
+ "javascript": "g.mergeV(new Map([[T.label, \"person\"], [\"name\", \"marko\"]])).option(Merge.onMatch, new Map([[T.label, \"person\"]]))",
+ "python": "g.merge_v({ T.label: 'person', 'name': 'marko' }).option(Merge.on_match, { T.label: 'person' })"
+ },
+ {
+ "original": "g.V()",
+ "language": "g.V()",
+ "canonical": "g.V()",
+ "anonymized": "g.V()",
+ "dotnet": "g.V()",
+ "go": "g.V()",
+ "groovy": "g.V()",
+ "java": "g.V()",
+ "javascript": "g.V()",
+ "python": "g.V()"
+ },
+ {
+ "original": "g.V().hasLabel(\"person\").hasLabel(\"employee\")",
+ "language": "g.V().hasLabel(\"person\").hasLabel(\"employee\")",
+ "canonical": "g.V().hasLabel(\"person\").hasLabel(\"employee\")",
+ "anonymized": "g.V().hasLabel(string0).hasLabel(string1)",
+ "dotnet": "g.V().HasLabel(\"person\").HasLabel(\"employee\")",
+ "go": "g.V().HasLabel(\"person\").HasLabel(\"employee\")",
+ "groovy": "g.V().hasLabel(\"person\").hasLabel(\"employee\")",
+ "java": "g.V().hasLabel(\"person\").hasLabel(\"employee\")",
+ "javascript": "g.V().hasLabel(\"person\").hasLabel(\"employee\")",
+ "python": "g.V().has_label('person').has_label('employee')"
+ }
+ ]
+ },
{
"scenario": "g_V_age_min",
"traversals": [
@@ -43153,6 +43177,35 @@
}
]
},
+ {
+ "scenario": "g_V_dropLabelXnonExistentX_labels",
+ "traversals": [
+ {
+ "original": "g.addV(\"a\", \"b\")",
+ "language": "g.addV(\"a\", \"b\")",
+ "canonical": "g.addV(\"a\", \"b\")",
+ "anonymized": "g.addV(string0, string1)",
+ "dotnet": "g.AddV((string) \"a\", (string) \"b\")",
+ "go": "g.AddV(\"a\", \"b\")",
+ "groovy": "g.addV(\"a\", \"b\")",
+ "java": "g.addV(\"a\", \"b\")",
+ "javascript": "g.addV(\"a\", \"b\")",
+ "python": "g.add_v('a', 'b')"
+ },
+ {
+ "original": "g.V().dropLabel(\"xyz\").labels()",
+ "language": "g.V().dropLabel(\"xyz\").labels()",
+ "canonical": "g.V().dropLabel(\"xyz\").labels()",
+ "anonymized": "g.V().dropLabel(string0).labels()",
+ "dotnet": "g.V().DropLabel(\"xyz\").Labels()",
+ "go": "g.V().DropLabel(\"xyz\").Labels()",
+ "groovy": "g.V().dropLabel(\"xyz\").labels()",
+ "java": "g.V().dropLabel(\"xyz\").labels()",
+ "javascript": "g.V().dropLabel(\"xyz\").labels()",
+ "python": "g.V().drop_label('xyz').labels()"
+ }
+ ]
+ },
{
"scenario": "g_V_fail",
"traversals": [
diff --git a/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/test/features/map/Labels.feature b/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/test/features/map/Labels.feature
index 322d0ca42c..b77385931b 100644
--- a/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/test/features/map/Labels.feature
+++ b/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/test/features/map/Labels.feature
@@ -50,20 +50,6 @@ Feature: Step - labels()
| a |
| b |
- @MultiLabel
- Scenario: g_addVXa_bX_labels_fold
- Given the empty graph
- And the graph initializer of
- """
- g.addV("a", "b")
- """
- And the traversal of
- """
- g.V().labels().fold()
- """
- When iterated to list
- Then the result should have a count of 1
-
@MultiLabel
Scenario: g_addVXa_bX_labels_count
Given the empty graph
@@ -92,9 +78,7 @@ Feature: Step - labels()
g.V().labels()
"""
When iterated to list
- Then the result should be unordered
- | result |
- | vertex |
+ Then the result should have a count of 0
@MultiLabel
Scenario: g_E_labels
diff --git a/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/test/features/map/MergeVertex.feature b/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/test/features/map/MergeVertex.feature
index eb95e6d3e2..d056fce1c7 100644
--- a/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/test/features/map/MergeVertex.feature
+++ b/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/test/features/map/MergeVertex.feature
@@ -1016,19 +1016,6 @@ Feature: Step - mergeV()
And the graph should return 1 for count of "g.V()"
And the graph should return 1 for count of "g.V().hasLabel(\"a\").hasLabel(\"b\").hasLabel(\"c\")"
- @MultiLabel
- Scenario: g_mergeVXlabel_person_name_markoX_single_label
- Given the empty graph
- And the traversal of
- """
- g.mergeV([(T.label): "person", name: "marko"])
- """
- When iterated to list
- Then the result should have a count of 1
- And the graph should return 1 for count of "g.V()"
- And the graph should return 1 for count of "g.V().hasLabel(\"person\")"
- And the graph should return 1 for count of "g.V().has(\"name\",\"marko\")"
-
@MultiLabel
Scenario: g_mergeVXlabel_ab_name_markoX_multilabel_match
Given the empty graph
@@ -1113,3 +1100,34 @@ Feature: Step - mergeV()
Then the result should have a count of 1
And the graph should return 1 for count of "g.V()"
And the graph should return 1 for count of "g.V().hasLabel(\"person\")"
+
+ @MultiLabel
+ Scenario: g_mergeVXname_markoX_optionXonCreate_label_ab_name_markoX
+ Given the empty graph
+ And the traversal of
+ """
+ g.mergeV([name: "marko"]).
+ option(Merge.onCreate, [(T.label): ["person","employee"], name: "marko"])
+ """
+ When iterated to list
+ Then the result should have a count of 1
+ And the graph should return 1 for count of "g.V()"
+ And the graph should return 1 for count of "g.V().hasLabel(\"person\").hasLabel(\"employee\")"
+ And the graph should return 1 for count of "g.V().has(\"name\",\"marko\")"
+
+ @MultiLabel
+ Scenario: g_mergeVXlabel_person_name_markoX_optionXonMatch_label_existingX
+ Given the empty graph
+ And the graph initializer of
+ """
+ g.addV("person").addLabel("employee").property("name", "marko")
+ """
+ And the traversal of
+ """
+ g.mergeV([(T.label): "person", name: "marko"]).
+ option(Merge.onMatch, [(T.label): "person"])
+ """
+ When iterated to list
+ Then the result should have a count of 1
+ And the graph should return 1 for count of "g.V()"
+ And the graph should return 1 for count of "g.V().hasLabel(\"person\").hasLabel(\"employee\")"
diff --git a/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/test/features/sideEffect/AddLabel.feature b/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/test/features/sideEffect/AddLabel.feature
index 0837669796..ec12441f1e 100644
--- a/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/test/features/sideEffect/AddLabel.feature
+++ b/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/test/features/sideEffect/AddLabel.feature
@@ -77,4 +77,4 @@ Feature: Step - addLabel()
g.E().addLabel("friend").labels().fold()
"""
When iterated to list
- Then the traversal will raise an error with message containing text of "Cannot add label"
+ Then the traversal will raise an error with message containing text of "Label mutation is not supported"
diff --git a/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/test/features/sideEffect/DropLabel.feature b/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/test/features/sideEffect/DropLabel.feature
index c96e375cde..bc28f41027 100644
--- a/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/test/features/sideEffect/DropLabel.feature
+++ b/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/test/features/sideEffect/DropLabel.feature
@@ -90,7 +90,7 @@ Feature: Step - dropLabel() / dropLabels()
g.E().dropLabel("knows").labels().fold()
"""
When iterated to list
- Then the result should have a count of 1
+ Then the traversal will raise an error with message containing text of "Label mutation is not supported"
@MultiLabel
Scenario: g_E_dropLabels_labels
@@ -104,4 +104,21 @@ Feature: Step - dropLabel() / dropLabels()
g.E().dropLabels().labels()
"""
When iterated to list
- Then the result should have a count of 0
+ Then the traversal will raise an error with message containing text of "Label mutation is not supported"
+
+ @MultiLabel
+ Scenario: g_V_dropLabelXnonExistentX_labels
+ Given the empty graph
+ And the graph initializer of
+ """
+ g.addV("a", "b")
+ """
+ And the traversal of
+ """
+ g.V().dropLabel("xyz").labels()
+ """
+ When iterated to list
+ Then the result should be unordered
+ | result |
+ | a |
+ | b |
diff --git a/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/AbstractTinkerGraph.java b/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/AbstractTinkerGraph.java
index 4a16f15df0..f786eda09d 100644
--- a/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/AbstractTinkerGraph.java
+++ b/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/AbstractTinkerGraph.java
@@ -66,7 +66,6 @@ public abstract class AbstractTinkerGraph implements Graph {
public static final String GREMLIN_TINKERGRAPH_ALLOW_NULL_PROPERTY_VALUES = "gremlin.tinkergraph.allowNullPropertyValues";
public static final String GREMLIN_TINKERGRAPH_SERVICE = "gremlin.tinkergraph.service";
public static final String GREMLIN_TINKERGRAPH_VERTEX_LABEL_CARDINALITY = "gremlin.tinkergraph.vertexLabelCardinality";
- public static final String GREMLIN_TINKERGRAPH_EDGE_LABEL_CARDINALITY = "gremlin.tinkergraph.edgeLabelCardinality";
protected AtomicLong currentId = new AtomicLong(-1L);
protected Map<Object, VertexProperty> vertexProperties = new ConcurrentHashMap<>();
@@ -485,16 +484,6 @@ public abstract class AbstractTinkerGraph implements Graph {
public boolean willAllowId(final Object id) {
return edgeIdManager.allow(id);
}
-
- @Override
- public LabelCardinality getLabelCardinality() {
- return edgeLabelCardinality;
- }
-
- @Override
- public String getDefaultLabel() {
- return defaultEdgeLabel;
- }
}
public class TinkerGraphVertexPropertyFeatures implements Features.VertexPropertyFeatures {
diff --git a/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerGraph.java b/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerGraph.java
index b49c3af063..a87dea9255 100644
--- a/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerGraph.java
+++ b/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerGraph.java
@@ -94,9 +94,8 @@ public class TinkerGraph extends AbstractTinkerGraph {
allowNullPropertyValues = configuration.getBoolean(GREMLIN_TINKERGRAPH_ALLOW_NULL_PROPERTY_VALUES, false);
vertexLabelCardinality = LabelCardinality.valueOf(
- configuration.getString(GREMLIN_TINKERGRAPH_VERTEX_LABEL_CARDINALITY, LabelCardinality.ZERO_OR_MORE.name()));
- edgeLabelCardinality = LabelCardinality.valueOf(
- configuration.getString(GREMLIN_TINKERGRAPH_EDGE_LABEL_CARDINALITY, LabelCardinality.ZERO_OR_ONE.name()));
+ configuration.getString(GREMLIN_TINKERGRAPH_VERTEX_LABEL_CARDINALITY, LabelCardinality.ONE.name()));
+ edgeLabelCardinality = LabelCardinality.ONE;
defaultVertexLabel = Vertex.DEFAULT_LABEL;
defaultEdgeLabel = Edge.DEFAULT_LABEL;
@@ -149,8 +148,7 @@ public class TinkerGraph extends AbstractTinkerGraph {
public Vertex addVertex(final Object... keyValues) {
ElementHelper.legalPropertyKeyValueArray(keyValues);
Object idValue = vertexIdManager.convert(ElementHelper.getIdValue(keyValues).orElse(null));
- final Set<String> labels = ElementHelper.getLabelsValue(keyValues).orElse(
- Collections.singleton(defaultVertexLabel));
+ final Set<String> labels = ElementHelper.getLabelsValue(keyValues).orElse(null);
if (null != idValue) {
if (this.vertices.containsKey(idValue))
@@ -162,7 +160,9 @@ public class TinkerGraph extends AbstractTinkerGraph {
final Vertex vertex = createTinkerVertex(idValue, labels, this);
ElementHelper.attachProperties(vertex, VertexProperty.Cardinality.list, keyValues);
this.vertices.put(vertex.id(), vertex);
- vertexLabelCounts.computeIfAbsent(label, l -> new AtomicInteger()).incrementAndGet();
+ for (final String l : vertex.labels()) {
+ vertexLabelCounts.computeIfAbsent(l, k -> new AtomicInteger()).incrementAndGet();
+ }
return vertex;
}
@@ -171,8 +171,11 @@ public class TinkerGraph extends AbstractTinkerGraph {
public void removeVertex(final Object vertexId)
{
final Vertex removed = this.vertices.remove(vertexId);
- if (removed != null)
- vertexLabelCounts.computeIfPresent(removed.label(), (l, c) -> { c.decrementAndGet(); return c; });
+ if (removed != null) {
+ for (final String l : removed.labels()) {
+ vertexLabelCounts.computeIfPresent(l, (k, c) -> { c.decrementAndGet(); return c; });
+ }
+ }
}
@Override
diff --git a/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerTransactionGraph.java b/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerTransactionGraph.java
index d0b301e50d..6a8a0284a9 100644
--- a/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerTransactionGraph.java
+++ b/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerTransactionGraph.java
@@ -89,9 +89,8 @@ public final class TinkerTransactionGraph extends AbstractTinkerGraph {
allowNullPropertyValues = configuration.getBoolean(GREMLIN_TINKERGRAPH_ALLOW_NULL_PROPERTY_VALUES, false);
vertexLabelCardinality = LabelCardinality.valueOf(
- configuration.getString(GREMLIN_TINKERGRAPH_VERTEX_LABEL_CARDINALITY, LabelCardinality.ZERO_OR_MORE.name()));
- edgeLabelCardinality = LabelCardinality.valueOf(
- configuration.getString(GREMLIN_TINKERGRAPH_EDGE_LABEL_CARDINALITY, LabelCardinality.ZERO_OR_ONE.name()));
+ configuration.getString(GREMLIN_TINKERGRAPH_VERTEX_LABEL_CARDINALITY, LabelCardinality.ONE.name()));
+ edgeLabelCardinality = LabelCardinality.ONE;
defaultVertexLabel = Vertex.DEFAULT_LABEL;
defaultEdgeLabel = Edge.DEFAULT_LABEL;
@@ -147,8 +146,7 @@ public final class TinkerTransactionGraph extends AbstractTinkerGraph {
Object idValue = vertexIdManager.convert(ElementHelper.getIdValue(keyValues).orElse(null));
if (null == idValue)
idValue = vertexIdManager.getNextId(this);
- final Set<String> labels = ElementHelper.getLabelsValue(keyValues).orElse(
- Collections.singleton(defaultVertexLabel));
+ final Set<String> labels = ElementHelper.getLabelsValue(keyValues).orElse(null);
this.tx().readWrite();
final long txNumber = transaction.getTxNumber();
diff --git a/tinkergraph-gremlin/src/test/java/org/apache/tinkerpop/gremlin/tinkergraph/TinkerWorld.java b/tinkergraph-gremlin/src/test/java/org/apache/tinkerpop/gremlin/tinkergraph/TinkerWorld.java
index 1a6ff95e02..1b5b6518b8 100644
--- a/tinkergraph-gremlin/src/test/java/org/apache/tinkerpop/gremlin/tinkergraph/TinkerWorld.java
+++ b/tinkergraph-gremlin/src/test/java/org/apache/tinkerpop/gremlin/tinkergraph/TinkerWorld.java
@@ -65,6 +65,7 @@ public abstract class TinkerWorld implements World {
conf.setProperty(TinkerGraph.GREMLIN_TINKERGRAPH_VERTEX_ID_MANAGER, AbstractTinkerGraph.DefaultIdManager.INTEGER.name());
conf.setProperty(TinkerGraph.GREMLIN_TINKERGRAPH_EDGE_ID_MANAGER, AbstractTinkerGraph.DefaultIdManager.INTEGER.name());
conf.setProperty(TinkerGraph.GREMLIN_TINKERGRAPH_VERTEX_PROPERTY_ID_MANAGER, AbstractTinkerGraph.DefaultIdManager.LONG.name());
+ conf.setProperty(AbstractTinkerGraph.GREMLIN_TINKERGRAPH_VERTEX_LABEL_CARDINALITY, "ZERO_OR_MORE");
return conf;
}
diff --git a/tinkergraph-gremlin/src/test/java/org/apache/tinkerpop/gremlin/tinkergraph/process/traversal/step/map/LabelsStepTest.java b/tinkergraph-gremlin/src/test/java/org/apache/tinkerpop/gremlin/tinkergraph/process/traversal/step/map/LabelsStepTest.java
index 9c816cf9c8..e4d98aa5a4 100644
--- a/tinkergraph-gremlin/src/test/java/org/apache/tinkerpop/gremlin/tinkergraph/process/traversal/step/map/LabelsStepTest.java
+++ b/tinkergraph-gremlin/src/test/java/org/apache/tinkerpop/gremlin/tinkergraph/process/traversal/step/map/LabelsStepTest.java
@@ -22,6 +22,7 @@ import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSo
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.apache.tinkerpop.gremlin.structure.Vertex;
+import org.apache.tinkerpop.gremlin.tinkergraph.structure.AbstractTinkerGraph;
import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph;
import org.junit.After;
import org.junit.Before;
@@ -46,7 +47,10 @@ public class LabelsStepTest {
@Before
public void setup() {
- graph = TinkerGraph.open();
+ final org.apache.commons.configuration2.Configuration config = new org.apache.commons.configuration2.BaseConfiguration();
+ config.setProperty(Graph.GRAPH, TinkerGraph.class.getName());
+ config.setProperty(AbstractTinkerGraph.GREMLIN_TINKERGRAPH_VERTEX_LABEL_CARDINALITY, "ZERO_OR_MORE");
+ graph = TinkerGraph.open(config);
g = graph.traversal();
}
@@ -63,21 +67,6 @@ public class LabelsStepTest {
assertThat(labels, containsInAnyOrder("person", "employee"));
}
- @Test
- public void shouldCountLabelsCorrectly() {
- final Vertex v = g.addV("person").addLabel("employee").next();
- final long count = g.V(v).labels().count().next();
- assertThat(count, is(2L));
- }
-
- @Test
- public void shouldFoldAllLabels() {
- final Vertex v = g.addV("person").addLabel("employee").next();
- final List<String> folded = g.V(v).labels().fold().next();
- assertThat(folded, hasSize(2));
- assertThat(folded, containsInAnyOrder("person", "employee"));
- }
-
@Test
public void shouldReturnSingletonForEdge() {
final Vertex v1 = g.addV("person").next();
@@ -100,7 +89,7 @@ public class LabelsStepTest {
public void shouldStreamDefaultLabelFromDefaultVertex() {
final Vertex v = g.addV().next();
final List<String> labels = g.V(v).labels().toList();
- assertThat(labels, hasSize(1));
- assertThat(labels, containsInAnyOrder(Vertex.DEFAULT_LABEL));
+ // Under ZERO_OR_MORE cardinality, addV() with no label produces an empty label set
+ assertThat(labels, hasSize(0));
}
}
diff --git a/tinkergraph-gremlin/src/test/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/LabelCardinalityTest.java b/tinkergraph-gremlin/src/test/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/LabelCardinalityTest.java
new file mode 100644
index 0000000000..e77170b60c
--- /dev/null
+++ b/tinkergraph-gremlin/src/test/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/LabelCardinalityTest.java
@@ -0,0 +1,318 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tinkerpop.gremlin.tinkergraph.structure;
+
+import org.apache.commons.configuration2.BaseConfiguration;
+import org.apache.commons.configuration2.Configuration;
+import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
+import org.apache.tinkerpop.gremlin.structure.Graph;
+import org.apache.tinkerpop.gremlin.structure.Vertex;
+import org.junit.Test;
+
+import java.util.Set;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.containsInAnyOrder;
+import static org.hamcrest.Matchers.empty;
+import static org.hamcrest.Matchers.hasSize;
+
+/**
+ * Tests for vertex label cardinality modes: ONE, ONE_OR_MORE, and ZERO_OR_MORE.
+ */
+public class LabelCardinalityTest {
+
+ // ========================================================================
+ // ONE mode (TinkerGraph default)
+ // ========================================================================
+
+ @Test
+ public void oneMode_addVNoLabel_shouldDefaultToVertex() throws Exception {
+ final Graph graph = TinkerGraph.open();
+ try {
+ final GraphTraversalSource g = graph.traversal();
+ final Vertex v = g.addV().next();
+ assertThat(v.labels(), hasSize(1));
+ assertThat(v.labels(), containsInAnyOrder(Vertex.DEFAULT_LABEL));
+ } finally {
+ graph.close();
+ }
+ }
+
+ @Test
+ public void oneMode_addVWithLabel_shouldHaveThatLabel() throws Exception {
+ final Graph graph = TinkerGraph.open();
+ try {
+ final GraphTraversalSource g = graph.traversal();
+ final Vertex v = g.addV("person").next();
+ assertThat(v.labels(), hasSize(1));
+ assertThat(v.labels(), containsInAnyOrder("person"));
+ } finally {
+ graph.close();
+ }
+ }
+
+ @Test(expected = IllegalStateException.class)
+ public void oneMode_addVWithMultipleLabels_shouldThrow() throws Exception {
+ final Graph graph = TinkerGraph.open();
+ try {
+ final GraphTraversalSource g = graph.traversal();
+ g.addV("a", "b").next();
+ } finally {
+ graph.close();
+ }
+ }
+
+ @Test(expected = IllegalStateException.class)
+ public void oneMode_addLabel_shouldThrow() throws Exception {
+ final Graph graph = TinkerGraph.open();
+ try {
+ final GraphTraversalSource g = graph.traversal();
+ final Vertex v = g.addV("person").next();
+ v.addLabel("x");
+ } finally {
+ graph.close();
+ }
+ }
+
+ @Test(expected = IllegalStateException.class)
+ public void oneMode_dropLabel_shouldThrow() throws Exception {
+ final Graph graph = TinkerGraph.open();
+ try {
+ final GraphTraversalSource g = graph.traversal();
+ final Vertex v = g.addV("person").next();
+ v.dropLabel(Vertex.DEFAULT_LABEL);
+ } finally {
+ graph.close();
+ }
+ }
+
+ @Test(expected = IllegalStateException.class)
+ public void oneMode_dropLabels_shouldThrow() throws Exception {
+ final Graph graph = TinkerGraph.open();
+ try {
+ final GraphTraversalSource g = graph.traversal();
+ final Vertex v = g.addV("person").next();
+ v.dropLabels();
+ } finally {
+ graph.close();
+ }
+ }
+
+ @Test(expected = IllegalStateException.class)
+ public void oneMode_addLabelViaTraversal_shouldThrow() throws Exception {
+ final Graph graph = TinkerGraph.open();
+ try {
+ final GraphTraversalSource g = graph.traversal();
+ g.addV("person").addLabel("x").iterate();
+ } finally {
+ graph.close();
+ }
+ }
+
+ @Test(expected = IllegalStateException.class)
+ public void oneMode_dropLabelViaTraversal_shouldThrow() throws Exception {
+ final Graph graph = TinkerGraph.open();
+ try {
+ final GraphTraversalSource g = graph.traversal();
+ g.addV("person").dropLabel("person").iterate();
+ } finally {
+ graph.close();
+ }
+ }
+
+ // ========================================================================
+ // ONE_OR_MORE mode
+ // ========================================================================
+
+ private Graph openOneOrMore() {
+ final Configuration config = new BaseConfiguration();
+ config.setProperty(Graph.GRAPH, TinkerGraph.class.getName());
+ config.setProperty(AbstractTinkerGraph.GREMLIN_TINKERGRAPH_VERTEX_LABEL_CARDINALITY, "ONE_OR_MORE");
+ return TinkerGraph.open(config);
+ }
+
+ @Test
+ public void oneOrMoreMode_addVNoLabel_shouldContainDefault() throws Exception {
+ final Graph graph = openOneOrMore();
+ try {
+ final GraphTraversalSource g = graph.traversal();
+ final Vertex v = g.addV().next();
+ assertThat(v.labels(), containsInAnyOrder(Vertex.DEFAULT_LABEL));
+ } finally {
+ graph.close();
+ }
+ }
+
+ @Test
+ public void oneOrMoreMode_addVWithLabel_shouldContainDefaultAndUserLabel() throws Exception {
+ final Graph graph = openOneOrMore();
+ try {
+ final GraphTraversalSource g = graph.traversal();
+ final Vertex v = g.addV("person").next();
+ assertThat(v.labels(), containsInAnyOrder(Vertex.DEFAULT_LABEL, "person"));
+ } finally {
+ graph.close();
+ }
+ }
+
+ @Test
+ public void oneOrMoreMode_addLabel_shouldAccumulate() throws Exception {
+ final Graph graph = openOneOrMore();
+ try {
+ final GraphTraversalSource g = graph.traversal();
+ final Vertex v = g.addV("person").next();
+ v.addLabel("employee");
+ assertThat(v.labels(), containsInAnyOrder(Vertex.DEFAULT_LABEL, "person", "employee"));
+ } finally {
+ graph.close();
+ }
+ }
+
+ @Test
+ public void oneOrMoreMode_dropLabel_shouldSucceedIfAtLeastOneRemains() throws Exception {
+ final Graph graph = openOneOrMore();
+ try {
+ final GraphTraversalSource g = graph.traversal();
+ final Vertex v = g.addV("person").next();
+ // Has {"vertex", "person"} — dropping "person" leaves {"vertex"}
+ v.dropLabel("person");
+ assertThat(v.labels(), containsInAnyOrder(Vertex.DEFAULT_LABEL));
+ } finally {
+ graph.close();
+ }
+ }
+
+ @Test(expected = IllegalStateException.class)
+ public void oneOrMoreMode_dropLabel_shouldThrowIfWouldLeaveZero() throws Exception {
+ final Graph graph = openOneOrMore();
+ try {
+ final GraphTraversalSource g = graph.traversal();
+ final Vertex v = g.addV().next();
+ // Has {"vertex"} — dropping "vertex" would leave 0
+ v.dropLabel(Vertex.DEFAULT_LABEL);
+ } finally {
+ graph.close();
+ }
+ }
+
+ @Test(expected = IllegalStateException.class)
+ public void oneOrMoreMode_dropMultipleLabels_shouldThrowIfWouldLeaveZero() throws Exception {
+ final Graph graph = openOneOrMore();
+ try {
+ final GraphTraversalSource g = graph.traversal();
+ final Vertex v = g.addV("person").next();
+ // Has {"vertex", "person"} — dropping both would leave 0
+ v.dropLabel("person", Vertex.DEFAULT_LABEL);
+ } finally {
+ graph.close();
+ }
+ }
+
+ @Test(expected = IllegalStateException.class)
+ public void oneOrMoreMode_dropLabels_shouldAlwaysThrow() throws Exception {
+ final Graph graph = openOneOrMore();
+ try {
+ final GraphTraversalSource g = graph.traversal();
+ final Vertex v = g.addV("person").next();
+ v.dropLabels();
+ } finally {
+ graph.close();
+ }
+ }
+
+ @Test
+ public void oneOrMoreMode_addVWithMultipleLabels_shouldIncludeDefault() throws Exception {
+ final Graph graph = openOneOrMore();
+ try {
+ final GraphTraversalSource g = graph.traversal();
+ final Vertex v = g.addV("a", "b").next();
+ assertThat(v.labels(), containsInAnyOrder(Vertex.DEFAULT_LABEL, "a", "b"));
+ } finally {
+ graph.close();
+ }
+ }
+
+ @Test
+ public void oneOrMoreMode_addDuplicateLabel_shouldBeNoOp() throws Exception {
+ final Graph graph = openOneOrMore();
+ try {
+ final GraphTraversalSource g = graph.traversal();
+ final Vertex v = g.addV("person").next();
+ // Has {"vertex", "person"}. Adding "person" again should be no-op.
+ v.addLabel("person");
+ assertThat(v.labels(), containsInAnyOrder(Vertex.DEFAULT_LABEL, "person"));
+ assertThat(v.labels(), hasSize(2));
+ } finally {
+ graph.close();
+ }
+ }
+
+ @Test
+ public void oneOrMoreMode_dropNonExistentLabel_shouldBeNoOp() throws Exception {
+ final Graph graph = openOneOrMore();
+ try {
+ final GraphTraversalSource g = graph.traversal();
+ final Vertex v = g.addV("person").next();
+ // Has {"vertex", "person"}. Dropping "nonexistent" should be no-op.
+ v.dropLabel("nonexistent");
+ assertThat(v.labels(), containsInAnyOrder(Vertex.DEFAULT_LABEL, "person"));
+ assertThat(v.labels(), hasSize(2));
+ } finally {
+ graph.close();
+ }
+ }
+
+ // ========================================================================
+ // ZERO_OR_MORE mode
+ // ========================================================================
+
+ private Graph openZeroOrMore() {
+ final Configuration config = new BaseConfiguration();
+ config.setProperty(Graph.GRAPH, TinkerGraph.class.getName());
+ config.setProperty(AbstractTinkerGraph.GREMLIN_TINKERGRAPH_VERTEX_LABEL_CARDINALITY, "ZERO_OR_MORE");
+ return TinkerGraph.open(config);
+ }
+
+ @Test
+ public void zeroOrMoreMode_labelSingular_shouldReturnEmptyStringForNoLabels() throws Exception {
+ final Graph graph = openZeroOrMore();
+ try {
+ final GraphTraversalSource g = graph.traversal();
+ final Vertex v = g.addV().next();
+ assertThat(v.labels(), is(empty()));
+ // label() (singular, deprecated) should return "" not null
+ assertThat(v.label(), isString(""));
+ } finally {
+ graph.close();
+ }
+ }
+
+ // helper for static import of Matchers.is and empty
+ private static org.hamcrest.Matcher<java.util.Collection<?>> is(org.hamcrest.Matcher<java.util.Collection<?>> matcher) {
+ return org.hamcrest.Matchers.is(matcher);
+ }
+
+ private static org.hamcrest.Matcher<java.util.Collection<?>> empty() {
+ return org.hamcrest.Matchers.empty();
+ }
+
+ private static org.hamcrest.Matcher<String> isString(final String expected) {
+ return org.hamcrest.Matchers.is(expected);
+ }
+}
diff --git a/tinkergraph-gremlin/src/test/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerVertexMultiLabelGremlinLangTest.java b/tinkergraph-gremlin/src/test/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerVertexMultiLabelGremlinLangTest.java
index 99d373bcdd..8d30574624 100644
--- a/tinkergraph-gremlin/src/test/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerVertexMultiLabelGremlinLangTest.java
+++ b/tinkergraph-gremlin/src/test/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerVertexMultiLabelGremlinLangTest.java
@@ -23,6 +23,8 @@ import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.apache.tinkerpop.gremlin.structure.Vertex;
+import org.apache.tinkerpop.gremlin.tinkergraph.structure.AbstractTinkerGraph;
+import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@@ -48,7 +50,10 @@ public class TinkerVertexMultiLabelGremlinLangTest {
@Before
public void setup() {
- graph = TinkerGraph.open();
+ final org.apache.commons.configuration2.Configuration config = new org.apache.commons.configuration2.BaseConfiguration();
+ config.setProperty(Graph.GRAPH, TinkerGraph.class.getName());
+ config.setProperty(AbstractTinkerGraph.GREMLIN_TINKERGRAPH_VERTEX_LABEL_CARDINALITY, "ZERO_OR_MORE");
+ graph = TinkerGraph.open(config);
g = graph.traversal();
}
@@ -105,17 +110,4 @@ public class TinkerVertexMultiLabelGremlinLangTest {
remoteG.close();
}
}
-
- @Test
- public void shouldNotDuplicateVerticesOnRepeatedEmbeddedRemoteCalls() throws Exception {
- final GraphTraversalSource remoteG = traversal().with(new EmbeddedRemoteConnection(g));
- try {
- remoteG.addV("a", "b").iterate();
- remoteG.addV("a", "b").iterate();
- final long count = g.V().count().next();
- assertThat(count, is(2L));
- } finally {
- remoteG.close();
- }
- }
}
(tinkerpop) 01/05: Implement multi-label prototype for vertices
Posted by xi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
xiazcy pushed a commit to branch multi-label-experiment
in repository https://gitbox.apache.org/repos/asf/tinkerpop.git
commit ed4c9ba663b143afd5526bd31f4a3f7e4cb1b78e
Author: Yang Xia <xi...@gmail.com>
AuthorDate: Thu Jun 25 02:18:15 2026 -0700
Implement multi-label prototype for vertices
Add support for multiple labels on vertices including:
- labels() step to retrieve vertex labels as individual traversers
- addLabel()/dropLabels()/dropLabel() mutation steps
- Element.labels() API addition
- Grammar updates for label operations
- Binary and GraphSON V4 serialization for multi-label vertices
- MergeVertex support for multi-label
- TinkerGraph implementation with thread-safe label storage
- Unit tests for label mutation, property interactions, and Gremlin lang
---
.../grammar/DefaultGremlinBaseVisitor.java | 28 +++
.../language/grammar/TraversalMethodVisitor.java | 94 ++++++++
.../grammar/TraversalSourceSpawnMethodVisitor.java | 28 ++-
.../process/computer/util/ComputerGraph.java | 5 +
.../traversal/dsl/graph/GraphTraversal.java | 112 ++++++++++
.../traversal/dsl/graph/GraphTraversalSource.java | 28 +++
.../gremlin/process/traversal/dsl/graph/__.java | 49 +++++
.../process/traversal/step/map/ElementMapStep.java | 39 +++-
.../process/traversal/step/map/LabelsStep.java | 53 +++++
.../traversal/step/map/MergeElementStep.java | 59 ++++-
.../traversal/step/map/MergeVertexStep.java | 28 ++-
.../traversal/step/map/PropertyMapStep.java | 23 +-
.../traversal/step/sideEffect/AddLabelStep.java | 147 +++++++++++++
.../traversal/step/sideEffect/DropLabelsStep.java | 158 +++++++++++++
.../process/traversal/step/util/HasContainer.java | 9 +-
.../process/traversal/step/util/WithOptions.java | 11 +
.../tinkerpop/gremlin/structure/Element.java | 56 +++++
.../gremlin/structure/VertexProperty.java | 14 ++
.../io/binary/types/VertexSerializer.java | 25 ++-
.../io/graphson/GraphSONSerializersV4.java | 22 +-
.../gremlin/structure/util/ElementHelper.java | 37 ++++
.../structure/util/detached/DetachedVertex.java | 40 ++++
.../structure/util/reference/ReferenceVertex.java | 35 +++
.../gremlin/structure/util/star/StarGraph.java | 5 +
gremlin-language/src/main/antlr4/Gremlin.g4 | 30 +++
.../ser/binary/TypeSerializerFailureTests.java | 2 +-
.../tinkergraph/structure/AbstractTinkerGraph.java | 24 ++
.../gremlin/tinkergraph/structure/TinkerEdge.java | 5 +
.../gremlin/tinkergraph/structure/TinkerGraph.java | 5 +-
.../tinkergraph/structure/TinkerVertex.java | 79 ++++++-
.../process/traversal/step/map/LabelsStepTest.java | 106 +++++++++
.../traversal/step/map/MergeVMultiLabelTest.java | 154 +++++++++++++
.../step/sideEffect/LabelMutationPropertyTest.java | 205 +++++++++++++++++
.../step/sideEffect/LabelMutationStepTest.java | 245 +++++++++++++++++++++
.../TinkerVertexMultiLabelGremlinLangTest.java | 121 ++++++++++
.../structure/TinkerVertexMultiLabelTest.java | 191 ++++++++++++++++
36 files changed, 2236 insertions(+), 36 deletions(-)
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/language/grammar/DefaultGremlinBaseVisitor.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/language/grammar/DefaultGremlinBaseVisitor.java
index 0431a36f05..10a35ec518 100644
--- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/language/grammar/DefaultGremlinBaseVisitor.java
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/language/grammar/DefaultGremlinBaseVisitor.java
@@ -183,6 +183,10 @@ public class DefaultGremlinBaseVisitor<T> extends AbstractParseTreeVisitor<T> im
* {@inheritDoc}
*/
@Override public T visitTraversalMethod_addV_Traversal(final GremlinParser.TraversalMethod_addV_TraversalContext ctx) { notImplemented(ctx); return null; }
+ /**
+ * {@inheritDoc}
+ */
+ @Override public T visitTraversalMethod_addV_StringVarargs(final GremlinParser.TraversalMethod_addV_StringVarargsContext ctx) { notImplemented(ctx); return null; }
/**
* {@inheritDoc}
*/
@@ -539,6 +543,30 @@ public class DefaultGremlinBaseVisitor<T> extends AbstractParseTreeVisitor<T> im
* {@inheritDoc}
*/
@Override public T visitTraversalMethod_label(final GremlinParser.TraversalMethod_labelContext ctx) { notImplemented(ctx); return null; }
+ /**
+ * {@inheritDoc}
+ */
+ @Override public T visitTraversalMethod_labels(final GremlinParser.TraversalMethod_labelsContext ctx) { notImplemented(ctx); return null; }
+ /**
+ * {@inheritDoc}
+ */
+ @Override public T visitTraversalMethod_addLabel_String(final GremlinParser.TraversalMethod_addLabel_StringContext ctx) { notImplemented(ctx); return null; }
+ /**
+ * {@inheritDoc}
+ */
+ @Override public T visitTraversalMethod_addLabel_Traversal(final GremlinParser.TraversalMethod_addLabel_TraversalContext ctx) { notImplemented(ctx); return null; }
+ /**
+ * {@inheritDoc}
+ */
+ @Override public T visitTraversalMethod_dropLabels_Empty(final GremlinParser.TraversalMethod_dropLabels_EmptyContext ctx) { notImplemented(ctx); return null; }
+ /**
+ * {@inheritDoc}
+ */
+ @Override public T visitTraversalMethod_dropLabel_String(final GremlinParser.TraversalMethod_dropLabel_StringContext ctx) { notImplemented(ctx); return null; }
+ /**
+ * {@inheritDoc}
+ */
+ @Override public T visitTraversalMethod_dropLabel_Traversal(final GremlinParser.TraversalMethod_dropLabel_TraversalContext ctx) { notImplemented(ctx); return null; }
/**
* {@inheritDoc}
*/
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/language/grammar/TraversalMethodVisitor.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/language/grammar/TraversalMethodVisitor.java
index 2c4980224a..216af370b4 100644
--- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/language/grammar/TraversalMethodVisitor.java
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/language/grammar/TraversalMethodVisitor.java
@@ -34,6 +34,7 @@ import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.VertexProperty.Cardinality;
import java.util.Arrays;
+import java.util.List;
import java.util.Map;
import java.util.function.BiFunction;
@@ -97,6 +98,25 @@ public class TraversalMethodVisitor extends TraversalRootVisitor<GraphTraversal>
}
}
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public GraphTraversal visitTraversalMethod_addV_StringVarargs(final GremlinParser.TraversalMethod_addV_StringVarargsContext ctx) {
+ final List<GremlinParser.StringArgumentContext> args = ctx.stringArgument();
+ final Object firstLiteralOrVar = antlr.argumentVisitor.visitStringArgument(args.get(0));
+ final String firstLabel = firstLiteralOrVar instanceof String ? (String) firstLiteralOrVar : ((GValue<String>) firstLiteralOrVar).get();
+ final Object secondLiteralOrVar = antlr.argumentVisitor.visitStringArgument(args.get(1));
+ final String secondLabel = secondLiteralOrVar instanceof String ? (String) secondLiteralOrVar : ((GValue<String>) secondLiteralOrVar).get();
+
+ final String[] moreLabels = new String[args.size() - 2];
+ for (int i = 2; i < args.size(); i++) {
+ final Object literalOrVar = antlr.argumentVisitor.visitStringArgument(args.get(i));
+ moreLabels[i - 2] = literalOrVar instanceof String ? (String) literalOrVar : ((GValue<String>) literalOrVar).get();
+ }
+ return this.graphTraversal.addV(firstLabel, secondLabel, moreLabels);
+ }
+
/**
* {@inheritDoc}
*/
@@ -978,6 +998,80 @@ public class TraversalMethodVisitor extends TraversalRootVisitor<GraphTraversal>
return graphTraversal.label();
}
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public GraphTraversal visitTraversalMethod_labels(final GremlinParser.TraversalMethod_labelsContext ctx) {
+ return graphTraversal.labels();
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public GraphTraversal visitTraversalMethod_addLabel_String(final GremlinParser.TraversalMethod_addLabel_StringContext ctx) {
+ final List<GremlinParser.StringArgumentContext> args = ctx.stringArgument();
+ final Object firstLiteralOrVar = antlr.argumentVisitor.visitStringArgument(args.get(0));
+ final String firstLabel = firstLiteralOrVar instanceof String ? (String) firstLiteralOrVar : ((GValue<String>) firstLiteralOrVar).get();
+
+ if (args.size() == 1) {
+ return this.graphTraversal.addLabel(firstLabel);
+ } else {
+ final String[] moreLabels = new String[args.size() - 1];
+ for (int i = 1; i < args.size(); i++) {
+ final Object literalOrVar = antlr.argumentVisitor.visitStringArgument(args.get(i));
+ moreLabels[i - 1] = literalOrVar instanceof String ? (String) literalOrVar : ((GValue<String>) literalOrVar).get();
+ }
+ return this.graphTraversal.addLabel(firstLabel, moreLabels);
+ }
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public GraphTraversal visitTraversalMethod_addLabel_Traversal(final GremlinParser.TraversalMethod_addLabel_TraversalContext ctx) {
+ return this.graphTraversal.addLabel(antlr.tvisitor.visitNestedTraversal(ctx.nestedTraversal()));
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public GraphTraversal visitTraversalMethod_dropLabels_Empty(final GremlinParser.TraversalMethod_dropLabels_EmptyContext ctx) {
+ return this.graphTraversal.dropLabels();
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public GraphTraversal visitTraversalMethod_dropLabel_String(final GremlinParser.TraversalMethod_dropLabel_StringContext ctx) {
+ final List<GremlinParser.StringArgumentContext> args = ctx.stringArgument();
+ final Object firstLiteralOrVar = antlr.argumentVisitor.visitStringArgument(args.get(0));
+ final String firstLabel = firstLiteralOrVar instanceof String ? (String) firstLiteralOrVar : ((GValue<String>) firstLiteralOrVar).get();
+
+ if (args.size() == 1) {
+ return this.graphTraversal.dropLabel(firstLabel);
+ } else {
+ final String[] moreLabels = new String[args.size() - 1];
+ for (int i = 1; i < args.size(); i++) {
+ final Object literalOrVar = antlr.argumentVisitor.visitStringArgument(args.get(i));
+ moreLabels[i - 1] = literalOrVar instanceof String ? (String) literalOrVar : ((GValue<String>) literalOrVar).get();
+ }
+ return this.graphTraversal.dropLabel(firstLabel, moreLabels);
+ }
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public GraphTraversal visitTraversalMethod_dropLabel_Traversal(final GremlinParser.TraversalMethod_dropLabel_TraversalContext ctx) {
+ return this.graphTraversal.dropLabel(antlr.tvisitor.visitNestedTraversal(ctx.nestedTraversal()));
+ }
+
/**
* {@inheritDoc}
*/
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/language/grammar/TraversalSourceSpawnMethodVisitor.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/language/grammar/TraversalSourceSpawnMethodVisitor.java
index 1b70a58c8d..9ac0e9a3fe 100644
--- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/language/grammar/TraversalSourceSpawnMethodVisitor.java
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/language/grammar/TraversalSourceSpawnMethodVisitor.java
@@ -22,6 +22,7 @@ import org.apache.tinkerpop.gremlin.process.traversal.Traversal;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.process.traversal.step.GValue;
+import java.util.List;
import java.util.Map;
/**
@@ -75,12 +76,29 @@ public class TraversalSourceSpawnMethodVisitor extends DefaultGremlinBaseVisitor
*/
@Override
public GraphTraversal visitTraversalSourceSpawnMethod_addV(final GremlinParser.TraversalSourceSpawnMethod_addVContext ctx) {
- if (ctx.stringArgument() != null) {
- final Object literalOrVar = antlr.argumentVisitor.visitStringArgument(ctx.stringArgument());
- if (GValue.valueInstanceOf(literalOrVar, String.class)) {
- return this.traversalSource.addV((GValue<String>) literalOrVar);
+ final List<GremlinParser.StringArgumentContext> stringArgs = ctx.stringArgument();
+ if (stringArgs != null && !stringArgs.isEmpty()) {
+ if (stringArgs.size() == 1) {
+ final Object literalOrVar = antlr.argumentVisitor.visitStringArgument(stringArgs.get(0));
+ if (GValue.valueInstanceOf(literalOrVar, String.class)) {
+ return this.traversalSource.addV((GValue<String>) literalOrVar);
+ } else {
+ return this.traversalSource.addV((String) literalOrVar);
+ }
} else {
- return this.traversalSource.addV((String) literalOrVar);
+ // Multi-label: addV("a", "b", ...)
+ final Object firstLiteralOrVar = antlr.argumentVisitor.visitStringArgument(stringArgs.get(0));
+ final String firstLabel = firstLiteralOrVar instanceof String ? (String) firstLiteralOrVar : ((GValue<String>) firstLiteralOrVar).get();
+ // Create vertex with first label, then add remaining labels
+ GraphTraversal t = this.traversalSource.addV(firstLabel);
+ final Object secondLiteralOrVar = antlr.argumentVisitor.visitStringArgument(stringArgs.get(1));
+ final String secondLabel = secondLiteralOrVar instanceof String ? (String) secondLiteralOrVar : ((GValue<String>) secondLiteralOrVar).get();
+ final String[] moreLabels = new String[stringArgs.size() - 2];
+ for (int i = 2; i < stringArgs.size(); i++) {
+ final Object literalOrVar = antlr.argumentVisitor.visitStringArgument(stringArgs.get(i));
+ moreLabels[i - 2] = literalOrVar instanceof String ? (String) literalOrVar : ((GValue<String>) literalOrVar).get();
+ }
+ return t.addLabel(secondLabel, moreLabels);
}
} else if (ctx.nestedTraversal() != null) {
return this.traversalSource.addV(anonymousVisitor.visitNestedTraversal(ctx.nestedTraversal()));
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/computer/util/ComputerGraph.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/computer/util/ComputerGraph.java
index 3a8a29e743..5634cbbc09 100644
--- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/computer/util/ComputerGraph.java
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/computer/util/ComputerGraph.java
@@ -456,6 +456,11 @@ public final class ComputerGraph implements Graph {
throw GraphComputer.Exceptions.adjacentVertexLabelsCanNotBeRead();
}
+ @Override
+ public Set<String> labels() {
+ throw GraphComputer.Exceptions.adjacentVertexLabelsCanNotBeRead();
+ }
+
@Override
public Graph graph() {
return ComputerGraph.this;
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/dsl/graph/GraphTraversal.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/dsl/graph/GraphTraversal.java
index df50a92462..72f08763d1 100644
--- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/dsl/graph/GraphTraversal.java
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/dsl/graph/GraphTraversal.java
@@ -66,6 +66,8 @@ import org.apache.tinkerpop.gremlin.process.traversal.step.map.MergeVertexStepPl
import org.apache.tinkerpop.gremlin.process.traversal.step.PropertiesHolder;
import org.apache.tinkerpop.gremlin.process.traversal.step.map.VertexStepPlaceholder;
import org.apache.tinkerpop.gremlin.process.traversal.step.sideEffect.AddPropertyStepPlaceholder;
+import org.apache.tinkerpop.gremlin.process.traversal.step.sideEffect.AddLabelStep;
+import org.apache.tinkerpop.gremlin.process.traversal.step.sideEffect.DropLabelsStep;
import org.apache.tinkerpop.gremlin.process.traversal.step.map.AddEdgeStepContract;
import org.apache.tinkerpop.gremlin.process.traversal.step.sideEffect.AddPropertyStepContract;
import org.apache.tinkerpop.gremlin.process.traversal.step.FromToModulating;
@@ -133,6 +135,7 @@ import org.apache.tinkerpop.gremlin.process.traversal.step.map.IntersectStep;
import org.apache.tinkerpop.gremlin.process.traversal.step.map.LTrimGlobalStep;
import org.apache.tinkerpop.gremlin.process.traversal.step.map.LTrimLocalStep;
import org.apache.tinkerpop.gremlin.process.traversal.step.map.LabelStep;
+import org.apache.tinkerpop.gremlin.process.traversal.step.map.LabelsStep;
import org.apache.tinkerpop.gremlin.process.traversal.step.map.LambdaCollectingBarrierStep;
import org.apache.tinkerpop.gremlin.process.traversal.step.map.LambdaFlatMapStep;
import org.apache.tinkerpop.gremlin.process.traversal.step.map.LambdaMapStep;
@@ -351,12 +354,26 @@ public interface GraphTraversal<S, E> extends Traversal<S, E> {
* @return the traversal with an appended {@link LabelStep}.
* @see <a href="http://tinkerpop.apache.org/docs/${project.version}/reference/#label-step" target="_blank">Reference Documentation - Label Step</a>
* @since 3.0.0-incubating
+ * @deprecated As of release 4.0.0, replaced by {@link #labels()}.
*/
+ @Deprecated
public default GraphTraversal<S, String> label() {
this.asAdmin().getGremlinLang().addStep(Symbols.label);
return this.asAdmin().addStep(new LabelStep<>(this.asAdmin()));
}
+ /**
+ * Map the {@link Element} to its labels, emitting each label as a separate traverser.
+ * For vertices with multiple labels, each label is emitted individually.
+ *
+ * @return the traversal with an appended {@link LabelsStep}.
+ * @since 4.0.0
+ */
+ public default GraphTraversal<S, String> labels() {
+ this.asAdmin().getGremlinLang().addStep(Symbols.labels);
+ return this.asAdmin().addStep(new LabelsStep<>(this.asAdmin()));
+ }
+
/**
* Map the <code>E</code> object to itself. In other words, a "no op."
*
@@ -1466,6 +1483,31 @@ public interface GraphTraversal<S, E> extends Traversal<S, E> {
return this.asAdmin().addStep(new AddVertexStepPlaceholder<>(this.asAdmin(), (String) null));
}
+ /**
+ * Adds a {@link Vertex} with multiple labels. Use this method to create multi-labeled vertices.
+ * Creates the vertex with the first label, then adds the remaining labels.
+ *
+ * @param label1 the first label
+ * @param label2 the second label
+ * @param moreLabels additional labels
+ * @return the traversal with the {@link AddVertexStepContract} added
+ * @since 4.0.0
+ */
+ public default GraphTraversal<S, Vertex> addV(final String label1, final String label2, final String... moreLabels) {
+ if (null == label1) throw new IllegalArgumentException("vertexLabel cannot be null");
+ if (null == label2) throw new IllegalArgumentException("vertexLabel cannot be null");
+ for (final String l : moreLabels) {
+ if (null == l) throw new IllegalArgumentException("vertexLabel cannot be null");
+ }
+ this.asAdmin().getGremlinLang().addStep(Symbols.addV, label1, label2, moreLabels);
+ this.asAdmin().addStep(new AddVertexStepPlaceholder<>(this.asAdmin(), label1));
+ // Add the AddLabelStep directly to avoid double-recording in GremlinLang.
+ // The addV step above already recorded all labels; calling t.addLabel() would
+ // record an additional addLabel() step in GremlinLang, producing incorrect output
+ // like g.addV("a","b").addLabel("b") instead of g.addV("a","b").
+ return this.asAdmin().addStep(new AddLabelStep<>(this.asAdmin(), label2, moreLabels));
+ }
+
/**
* Performs a merge (i.e. upsert) style operation for an {@link Vertex} using the incoming {@code Map} traverser as
* an argument. The {@code Map} represents search criteria and will match each of the supplied key/value pairs where
@@ -3463,6 +3505,72 @@ public interface GraphTraversal<S, E> extends Traversal<S, E> {
return this.asAdmin().addStep(new DropStep<>(this.asAdmin()));
}
+ /**
+ * Adds one or more labels to the current element. This is a side-effect step that passes the
+ * element through unchanged.
+ *
+ * @param label the first label to add
+ * @param moreLabels additional labels to add
+ * @return the traversal with an appended {@link AddLabelStep}
+ * @since 4.0.0
+ */
+ public default GraphTraversal<S, E> addLabel(final String label, final String... moreLabels) {
+ this.asAdmin().getGremlinLang().addStep(Symbols.addLabel, label, moreLabels);
+ return this.asAdmin().addStep((AddLabelStep) new AddLabelStep<>(this.asAdmin(), label, moreLabels));
+ }
+
+ /**
+ * Adds dynamically computed labels to the current element. This is a side-effect step that passes the
+ * element through unchanged.
+ *
+ * @param labelTraversal the traversal that produces labels to add
+ * @return the traversal with an appended {@link AddLabelStep}
+ * @since 4.0.0
+ */
+ public default GraphTraversal<S, E> addLabel(final Traversal<?, String> labelTraversal) {
+ this.asAdmin().getGremlinLang().addStep(Symbols.addLabel, labelTraversal);
+ return this.asAdmin().addStep((AddLabelStep) new AddLabelStep(this.asAdmin(), labelTraversal.asAdmin()));
+ }
+
+ /**
+ * Removes all labels from the current element, triggering the provider's default label behavior.
+ * This is a side-effect step that passes the element through unchanged.
+ *
+ * @return the traversal with an appended {@link DropLabelsStep}
+ * @since 4.0.0
+ */
+ public default GraphTraversal<S, E> dropLabels() {
+ this.asAdmin().getGremlinLang().addStep(Symbols.dropLabels);
+ return this.asAdmin().addStep((DropLabelsStep) new DropLabelsStep<>(this.asAdmin()));
+ }
+
+ /**
+ * Removes specific labels from the current element. This is a side-effect step that passes the
+ * element through unchanged.
+ *
+ * @param label the first label to remove
+ * @param moreLabels additional labels to remove
+ * @return the traversal with an appended {@link DropLabelsStep}
+ * @since 4.0.0
+ */
+ public default GraphTraversal<S, E> dropLabel(final String label, final String... moreLabels) {
+ this.asAdmin().getGremlinLang().addStep(Symbols.dropLabel, label, moreLabels);
+ return this.asAdmin().addStep((DropLabelsStep) new DropLabelsStep<>(this.asAdmin(), label, moreLabels));
+ }
+
+ /**
+ * Removes a dynamically computed label from the current element. This is a side-effect step that passes the
+ * element through unchanged.
+ *
+ * @param labelTraversal the traversal that produces the label to remove
+ * @return the traversal with an appended {@link DropLabelsStep}
+ * @since 4.0.0
+ */
+ public default GraphTraversal<S, E> dropLabel(final Traversal<?, String> labelTraversal) {
+ this.asAdmin().getGremlinLang().addStep(Symbols.dropLabel, labelTraversal);
+ return this.asAdmin().addStep((DropLabelsStep) new DropLabelsStep(this.asAdmin(), labelTraversal.asAdmin()));
+ }
+
/**
* Filters <code>E</code> lists given the provided {@code predicate}.
*
@@ -4760,6 +4868,7 @@ public interface GraphTraversal<S, E> extends Traversal<S, E> {
public static final String flatMap = "flatMap";
public static final String id = "id";
public static final String label = "label";
+ public static final String labels = "labels";
public static final String identity = "identity";
public static final String constant = "constant";
public static final String V = "V";
@@ -4866,6 +4975,9 @@ public interface GraphTraversal<S, E> extends Traversal<S, E> {
public static final String sample = "sample";
public static final String drop = "drop";
+ public static final String addLabel = "addLabel";
+ public static final String dropLabels = "dropLabels";
+ public static final String dropLabel = "dropLabel";
public static final String sideEffect = "sideEffect";
public static final String cap = "cap";
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/dsl/graph/GraphTraversalSource.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/dsl/graph/GraphTraversalSource.java
index 7a4adb054a..0c7715f5af 100644
--- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/dsl/graph/GraphTraversalSource.java
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/dsl/graph/GraphTraversalSource.java
@@ -31,6 +31,7 @@ import org.apache.tinkerpop.gremlin.process.traversal.step.GValue;
import org.apache.tinkerpop.gremlin.process.traversal.step.branch.UnionStep;
import org.apache.tinkerpop.gremlin.process.traversal.step.map.AddEdgeStartStepPlaceholder;
import org.apache.tinkerpop.gremlin.process.traversal.step.map.AddVertexStartStepPlaceholder;
+import org.apache.tinkerpop.gremlin.process.traversal.step.sideEffect.AddLabelStep;
import org.apache.tinkerpop.gremlin.process.traversal.step.map.CallStep;
import org.apache.tinkerpop.gremlin.process.traversal.step.map.CallStepPlaceholder;
import org.apache.tinkerpop.gremlin.process.traversal.step.map.DeclarativeMatchStep;
@@ -367,6 +368,33 @@ public class GraphTraversalSource implements TraversalSource {
return traversal.addStep(new AddVertexStartStepPlaceholder(traversal, vertexLabel));
}
+ /**
+ * Spawns a {@link GraphTraversal} by adding a vertex with multiple labels.
+ * Creates the vertex with the first label, then adds the remaining labels.
+ *
+ * @param label1 the first label
+ * @param label2 the second label
+ * @param moreLabels additional labels
+ * @return the traversal with the vertex added
+ * @since 4.0.0
+ */
+ public GraphTraversal<Vertex, Vertex> addV(final String label1, final String label2, final String... moreLabels) {
+ if (null == label1) throw new IllegalArgumentException("vertexLabel cannot be null");
+ if (null == label2) throw new IllegalArgumentException("vertexLabel cannot be null");
+ for (final String l : moreLabels) {
+ if (null == l) throw new IllegalArgumentException("vertexLabel cannot be null");
+ }
+ final GraphTraversalSource clone = this.clone();
+ clone.gremlinLang.addStep(GraphTraversal.Symbols.addV, label1, label2, moreLabels);
+ final GraphTraversal.Admin<Vertex, Vertex> traversal = new DefaultGraphTraversal<>(clone);
+ traversal.addStep(new AddVertexStartStepPlaceholder(traversal, label1));
+ // Add the AddLabelStep directly to avoid double-recording in GremlinLang.
+ // The addV step above already recorded all labels; calling t.addLabel() would
+ // record an additional addLabel() step in GremlinLang, producing incorrect output
+ // like g.addV("a","b").addLabel("b") instead of g.addV("a","b").
+ return traversal.addStep(new AddLabelStep<>(traversal, label2, moreLabels));
+ }
+
/**
* Spawns a {@link GraphTraversal} by adding an edge with the specified label.
*
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/dsl/graph/__.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/dsl/graph/__.java
index 390c4cc48f..421a1f33ad 100644
--- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/dsl/graph/__.java
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/dsl/graph/__.java
@@ -128,6 +128,48 @@ public class __ {
return __.<A>start().label();
}
+ /**
+ * @see GraphTraversal#labels()
+ */
+ public static <A extends Element> GraphTraversal<A, String> labels() {
+ return __.<A>start().labels();
+ }
+
+ /**
+ * @see GraphTraversal#addLabel(String, String...)
+ */
+ public static <A extends Element> GraphTraversal<A, A> addLabel(final String label, final String... moreLabels) {
+ return __.<A>start().addLabel(label, moreLabels);
+ }
+
+ /**
+ * @see GraphTraversal#addLabel(Traversal)
+ */
+ public static <A extends Element> GraphTraversal<A, A> addLabel(final Traversal<?, String> labelTraversal) {
+ return __.<A>start().addLabel(labelTraversal);
+ }
+
+ /**
+ * @see GraphTraversal#dropLabels()
+ */
+ public static <A extends Element> GraphTraversal<A, A> dropLabels() {
+ return __.<A>start().dropLabels();
+ }
+
+ /**
+ * @see GraphTraversal#dropLabel(String, String...)
+ */
+ public static <A extends Element> GraphTraversal<A, A> dropLabel(final String label, final String... moreLabels) {
+ return __.<A>start().dropLabel(label, moreLabels);
+ }
+
+ /**
+ * @see GraphTraversal#dropLabel(Traversal)
+ */
+ public static <A extends Element> GraphTraversal<A, A> dropLabel(final Traversal<?, String> labelTraversal) {
+ return __.<A>start().dropLabel(labelTraversal);
+ }
+
/**
* @see GraphTraversal#id()
*/
@@ -672,6 +714,13 @@ public class __ {
return __.<A>start().addV();
}
+ /**
+ * @see GraphTraversal#addV(String, String, String...)
+ */
+ public static <A> GraphTraversal<A, Vertex> addV(final String label1, final String label2, final String... moreLabels) {
+ return __.<A>start().addV(label1, label2, moreLabels);
+ }
+
/**
* @see GraphTraversal#mergeV()
*/
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/ElementMapStep.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/ElementMapStep.java
index 972511a441..370b0cd059 100644
--- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/ElementMapStep.java
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/ElementMapStep.java
@@ -20,8 +20,12 @@ package org.apache.tinkerpop.gremlin.process.traversal.step.map;
import org.apache.tinkerpop.gremlin.process.traversal.Traversal;
import org.apache.tinkerpop.gremlin.process.traversal.Traverser;
+import org.apache.tinkerpop.gremlin.process.traversal.step.Configuring;
import org.apache.tinkerpop.gremlin.process.traversal.step.GraphComputing;
import org.apache.tinkerpop.gremlin.process.traversal.step.TraversalParent;
+import org.apache.tinkerpop.gremlin.process.traversal.step.util.Parameters;
+import org.apache.tinkerpop.gremlin.process.traversal.step.util.WithOptions;
+import org.apache.tinkerpop.gremlin.process.traversal.strategy.decoration.OptionsStrategy;
import org.apache.tinkerpop.gremlin.process.traversal.traverser.TraverserRequirement;
import org.apache.tinkerpop.gremlin.structure.Direction;
import org.apache.tinkerpop.gremlin.structure.Edge;
@@ -46,16 +50,32 @@ import java.util.Set;
* @author Daniel Kuppitz (http://gremlin.guru)
* @author Stephen Mallette (http://stephen.genoprime.com)
*/
-public class ElementMapStep<K,E> extends ScalarMapStep<Element, Map<K, E>> implements TraversalParent, GraphComputing {
+public class ElementMapStep<K,E> extends ScalarMapStep<Element, Map<K, E>> implements TraversalParent, GraphComputing, Configuring {
protected final String[] propertyKeys;
private boolean onGraphComputer = false;
+ private boolean multilabel = false;
+ private final Parameters parameters = new Parameters();
public ElementMapStep(final Traversal.Admin traversal, final String... propertyKeys) {
super(traversal);
this.propertyKeys = propertyKeys;
}
+ @Override
+ public void configure(final Object... keyValues) {
+ if (keyValues[0].equals(WithOptions.multilabel)) {
+ this.multilabel = true;
+ } else {
+ this.parameters.set(this, keyValues);
+ }
+ }
+
+ @Override
+ public Parameters getParameters() {
+ return this.parameters;
+ }
+
@Override
protected Map<K, E> map(final Traverser.Admin<Element> traverser) {
final Map<Object, Object> map = new LinkedHashMap<>();
@@ -65,7 +85,11 @@ public class ElementMapStep<K,E> extends ScalarMapStep<Element, Map<K, E>> imple
map.put(T.key, ((VertexProperty<?>) element).key());
map.put(T.value, ((VertexProperty<?>) element).value());
} else {
- map.put(T.label, element.label());
+ if (isMultilabelEnabled()) {
+ map.put(T.label, element.labels());
+ } else {
+ map.put(T.label, element.label());
+ }
}
if (element instanceof Edge) {
@@ -102,6 +126,17 @@ public class ElementMapStep<K,E> extends ScalarMapStep<Element, Map<K, E>> imple
return onGraphComputer;
}
+ /**
+ * Checks if multilabel mode is enabled either via step-level {@code .with(WithOptions.multilabel)}
+ * or source-level {@code g.with("multilabel")}.
+ */
+ private boolean isMultilabelEnabled() {
+ if (this.multilabel) return true;
+ return getTraversal().getStrategies().getStrategy(OptionsStrategy.class)
+ .map(os -> os.getOptions().containsKey("multilabel") || os.getOptions().containsKey(WithOptions.multilabel))
+ .orElse(false);
+ }
+
public String[] getPropertyKeys() {
return propertyKeys;
}
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/LabelsStep.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/LabelsStep.java
new file mode 100644
index 0000000000..a5ba807176
--- /dev/null
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/LabelsStep.java
@@ -0,0 +1,53 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tinkerpop.gremlin.process.traversal.step.map;
+
+import org.apache.tinkerpop.gremlin.process.traversal.Traversal;
+import org.apache.tinkerpop.gremlin.process.traversal.Traverser;
+import org.apache.tinkerpop.gremlin.process.traversal.traverser.TraverserRequirement;
+import org.apache.tinkerpop.gremlin.structure.Element;
+import org.apache.tinkerpop.gremlin.structure.util.StringFactory;
+
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.Set;
+
+/**
+ * Maps an {@link Element} to its labels, emitting each label as a separate traverser.
+ * For vertices with multiple labels, each label is emitted individually.
+ * For edges, the single label is emitted.
+ *
+ * @since 4.0.0
+ */
+public class LabelsStep<S extends Element> extends FlatMapStep<S, String> {
+
+ public LabelsStep(final Traversal.Admin traversal) {
+ super(traversal);
+ }
+
+ @Override
+ protected Iterator<String> flatMap(final Traverser.Admin<S> traverser) {
+ return traverser.get().labels().iterator();
+ }
+
+ @Override
+ public Set<TraverserRequirement> getRequirements() {
+ return Collections.singleton(TraverserRequirement.OBJECT);
+ }
+}
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/MergeElementStep.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/MergeElementStep.java
index 053213f96c..6b7c261d48 100644
--- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/MergeElementStep.java
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/MergeElementStep.java
@@ -254,7 +254,25 @@ public abstract class MergeElementStep<S, E, C> extends FlatMapStep<S, E>
final Object v = e.getValue();
if (ignoreTokens) {
- if (!(k instanceof String)) {
+ // Allow T.label in onMatch for multi-label replacement support
+ if (k == T.label) {
+ if (v instanceof String) {
+ ElementHelper.validateLabel((String) v);
+ } else if (v instanceof java.util.Collection) {
+ for (final Object label : (java.util.Collection<?>) v) {
+ if (!(label instanceof String)) {
+ throw new IllegalArgumentException(String.format(
+ "option(onMatch) expects T.label collection to contain only Strings - found: %s",
+ label.getClass().getSimpleName()));
+ }
+ ElementHelper.validateLabel((String) label);
+ }
+ } else {
+ throw new IllegalArgumentException(String.format(
+ "option(onMatch) expects T.label value to be String or Collection<String> - found: %s",
+ v.getClass().getSimpleName()));
+ }
+ } else if (!(k instanceof String)) {
throw new IllegalArgumentException(String.format("option(onMatch) expects keys in Map to be of String - check: %s", k));
} else {
ElementHelper.validateProperty((String) k, v);
@@ -271,12 +289,21 @@ public abstract class MergeElementStep<S, E, C> extends FlatMapStep<S, E>
op, allowedTokens, k));
}
if (k == T.label) {
- if (!(v instanceof String)) {
- throw new IllegalArgumentException(String.format(
- "%s() and option(onCreate) args expect T.label value to be of String - found: %s", op,
- v.getClass().getSimpleName()));
- } else {
+ if (v instanceof String) {
ElementHelper.validateLabel((String) v);
+ } else if (v instanceof java.util.Collection) {
+ for (final Object label : (java.util.Collection<?>) v) {
+ if (!(label instanceof String)) {
+ throw new IllegalArgumentException(String.format(
+ "%s() expects T.label collection to contain only Strings - found: %s",
+ op, label.getClass().getSimpleName()));
+ }
+ ElementHelper.validateLabel((String) label);
+ }
+ } else {
+ throw new IllegalArgumentException(String.format(
+ "%s() and option(onCreate) args expect T.label value to be String or Collection<String> - found: %s",
+ op, v.getClass().getSimpleName()));
}
}
if (k == Direction.OUT && v instanceof Merge && v != Merge.outV) {
@@ -337,10 +364,10 @@ public abstract class MergeElementStep<S, E, C> extends FlatMapStep<S, E>
final Graph graph = getGraph();
final Object id = search.get(T.id);
- final String label = (String) search.get(T.label);
+ final Object labelValue = search.get(T.label);
GraphTraversal t = searchVerticesTraversal(graph, id);
- t = searchVerticesLabelConstraint(t, label);
+ t = searchVerticesLabelConstraint(t, labelValue);
t = searchVerticesPropertyConstraints(t, search);
// this should auto-close the underlying traversal
@@ -351,8 +378,20 @@ public abstract class MergeElementStep<S, E, C> extends FlatMapStep<S, E>
return id != null ? graph.traversal().V(id) : graph.traversal().V();
}
- protected GraphTraversal searchVerticesLabelConstraint(GraphTraversal t, final String label) {
- return label != null ? t.hasLabel(label) : t;
+ protected GraphTraversal searchVerticesLabelConstraint(GraphTraversal t, final Object labelValue) {
+ if (labelValue == null) {
+ return t;
+ }
+ if (labelValue instanceof String) {
+ return t.hasLabel((String) labelValue);
+ } else if (labelValue instanceof java.util.Collection) {
+ // Multi-label: AND semantics - must have ALL specified labels
+ for (final Object label : (java.util.Collection<?>) labelValue) {
+ t = t.hasLabel((String) label);
+ }
+ return t;
+ }
+ return t;
}
protected GraphTraversal searchVerticesPropertyConstraints(GraphTraversal t, final Map search) {
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/MergeVertexStep.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/MergeVertexStep.java
index 118468236f..ad37175cd3 100644
--- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/MergeVertexStep.java
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/MergeVertexStep.java
@@ -99,12 +99,32 @@ public class MergeVertexStep<S> extends MergeElementStep<S, Vertex, Map<Object,
traverser.set((S) v);
// assume good input from GraphTraversal - folks might drop in a T here even though it is immutable
- final Map<String, Object> onMatchMap = materializeMap(traverser, onMatchTraversal);
+ final Map onMatchMap = materializeMap(traverser, onMatchTraversal);
validateMapInput(onMatchMap, true);
onMatchMap.forEach((key, value) -> {
+ // Handle T.label replacement for multi-label support
+ if (T.label.equals(key) || T.label.getAccessor().equals(key)) {
+ // Drop all existing labels and replace with new ones
+ v.dropLabels();
+ if (value instanceof String) {
+ v.addLabel((String) value);
+ } else if (value instanceof java.util.Collection) {
+ final java.util.Collection<?> labels = (java.util.Collection<?>) value;
+ if (!labels.isEmpty()) {
+ final String[] labelArray = labels.stream()
+ .map(l -> (String) l)
+ .toArray(String[]::new);
+ v.addLabel(labelArray[0],
+ java.util.Arrays.copyOfRange(labelArray, 1, labelArray.length));
+ }
+ // Empty collection = use default label behavior (already handled by dropLabels())
+ }
+ return;
+ }
+
Object val = value;
- VertexProperty.Cardinality card = graph.features().vertex().getCardinality(key);
+ VertexProperty.Cardinality card = graph.features().vertex().getCardinality((String) key);
// a value can be a traversal in the case where the user specifies the cardinality for the value.
if (value instanceof CardinalityValueTraversal) {
@@ -115,10 +135,10 @@ public class MergeVertexStep<S> extends MergeElementStep<S, Vertex, Map<Object,
// trigger callbacks for eventing - in this case, it's a VertexPropertyChangedEvent. if there's no
// registry/callbacks then just set the property
- EventUtil.registerVertexPropertyChange(callbackRegistry, getTraversal(), v, key, val);
+ EventUtil.registerVertexPropertyChange(callbackRegistry, getTraversal(), v, (String) key, val);
// try to detect proper cardinality for the key according to the graph
- v.property(card, key, val);
+ v.property(card, (String) key, val);
});
});
}
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/PropertyMapStep.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/PropertyMapStep.java
index 489fea8895..25bc143bc3 100644
--- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/PropertyMapStep.java
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/PropertyMapStep.java
@@ -25,6 +25,7 @@ import org.apache.tinkerpop.gremlin.process.traversal.step.Configuring;
import org.apache.tinkerpop.gremlin.process.traversal.step.TraversalParent;
import org.apache.tinkerpop.gremlin.process.traversal.step.util.Parameters;
import org.apache.tinkerpop.gremlin.process.traversal.step.util.WithOptions;
+import org.apache.tinkerpop.gremlin.process.traversal.strategy.decoration.OptionsStrategy;
import org.apache.tinkerpop.gremlin.process.traversal.traverser.TraverserRequirement;
import org.apache.tinkerpop.gremlin.process.traversal.util.TraversalProduct;
import org.apache.tinkerpop.gremlin.process.traversal.util.TraversalUtil;
@@ -58,6 +59,7 @@ public class PropertyMapStep<K,E> extends ScalarMapStep<Element, Map<K, E>>
protected int tokens;
protected Traversal.Admin<Element, ? extends Property> propertyTraversal;
+ protected boolean multilabel = false;
protected Parameters parameters = new Parameters();
protected Traversal.Admin<K, E> valueTraversal;
@@ -97,6 +99,8 @@ public class PropertyMapStep<K,E> extends ScalarMapStep<Element, Map<K, E>>
this.tokens |= (int) keyValues[i];
}
}
+ } else if (keyValues[0].equals(WithOptions.multilabel)) {
+ this.multilabel = true;
} else {
this.parameters.set(this, keyValues);
}
@@ -200,11 +204,28 @@ public class PropertyMapStep<K,E> extends ScalarMapStep<Element, Map<K, E>>
if (includeToken(WithOptions.keys)) map.put(T.key, getVertexPropertyKey((VertexProperty<?>) element));
if (includeToken(WithOptions.values)) map.put(T.value, getVertexPropertyValue((VertexProperty<?>) element));
} else {
- if (includeToken(WithOptions.labels)) map.put(T.label, getElementLabel(element));
+ if (includeToken(WithOptions.labels)) {
+ if (isMultilabelEnabled()) {
+ map.put(T.label, element.labels());
+ } else {
+ map.put(T.label, getElementLabel(element));
+ }
+ }
}
}
}
+ /**
+ * Checks if multilabel mode is enabled either via step-level {@code .with(WithOptions.multilabel)}
+ * or source-level {@code g.with("multilabel")}.
+ */
+ private boolean isMultilabelEnabled() {
+ if (this.multilabel) return true;
+ return getTraversal().getStrategies().getStrategy(OptionsStrategy.class)
+ .map(os -> os.getOptions().containsKey("multilabel") || os.getOptions().containsKey(WithOptions.multilabel))
+ .orElse(false);
+ }
+
protected Object getElementId(Element element){
return element.id();
}
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/sideEffect/AddLabelStep.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/sideEffect/AddLabelStep.java
new file mode 100644
index 0000000000..c239623601
--- /dev/null
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/sideEffect/AddLabelStep.java
@@ -0,0 +1,147 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tinkerpop.gremlin.process.traversal.step.sideEffect;
+
+import org.apache.tinkerpop.gremlin.process.traversal.Traversal;
+import org.apache.tinkerpop.gremlin.process.traversal.Traverser;
+import org.apache.tinkerpop.gremlin.process.traversal.step.Mutating;
+import org.apache.tinkerpop.gremlin.process.traversal.step.TraversalParent;
+import org.apache.tinkerpop.gremlin.process.traversal.step.util.event.CallbackRegistry;
+import org.apache.tinkerpop.gremlin.process.traversal.step.util.event.Event;
+import org.apache.tinkerpop.gremlin.process.traversal.step.util.event.EventUtil;
+import org.apache.tinkerpop.gremlin.process.traversal.step.util.event.ListCallbackRegistry;
+import org.apache.tinkerpop.gremlin.process.traversal.strategy.decoration.EventStrategy;
+import org.apache.tinkerpop.gremlin.process.traversal.traverser.TraverserRequirement;
+import org.apache.tinkerpop.gremlin.process.traversal.util.TraversalUtil;
+import org.apache.tinkerpop.gremlin.structure.Element;
+import org.apache.tinkerpop.gremlin.structure.util.ElementHelper;
+import org.apache.tinkerpop.gremlin.structure.util.StringFactory;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.Set;
+
+/**
+ * Side-effect step that adds labels to the current element by calling {@link Element#addLabel(String, String...)}.
+ * Providers that support label mutation must override {@code addLabel()} in their Element implementations.
+ *
+ * @since 4.0.0
+ */
+public class AddLabelStep<S extends Element> extends SideEffectStep<S>
+ implements Mutating<Event.ElementPropertyChangedEvent>, TraversalParent {
+
+ private final String[] labels;
+ private Traversal.Admin<S, String> labelTraversal;
+ private CallbackRegistry<Event.ElementPropertyChangedEvent> callbackRegistry;
+
+ public AddLabelStep(final Traversal.Admin traversal, final String label, final String... moreLabels) {
+ super(traversal);
+ ElementHelper.validateLabel(label);
+ for (final String l : moreLabels) {
+ ElementHelper.validateLabel(l);
+ }
+ final List<String> allLabels = new ArrayList<>();
+ allLabels.add(label);
+ allLabels.addAll(Arrays.asList(moreLabels));
+ this.labels = allLabels.toArray(new String[0]);
+ this.labelTraversal = null;
+ }
+
+ public AddLabelStep(final Traversal.Admin traversal, final Traversal.Admin<S, String> labelTraversal) {
+ super(traversal);
+ this.labels = null;
+ this.labelTraversal = this.integrateChild(labelTraversal);
+ }
+
+ @Override
+ protected void sideEffect(final Traverser.Admin<S> traverser) {
+ final Element element = traverser.get();
+
+ if (this.labelTraversal != null) {
+ final List<String> collectedLabels = new ArrayList<>();
+ TraversalUtil.applyAll(traverser, this.labelTraversal)
+ .forEachRemaining(label -> {
+ ElementHelper.validateLabel(label);
+ collectedLabels.add(label);
+ });
+ if (!collectedLabels.isEmpty()) {
+ element.addLabel(collectedLabels.get(0),
+ collectedLabels.subList(1, collectedLabels.size()).toArray(new String[0]));
+ }
+ } else {
+ element.addLabel(this.labels[0],
+ Arrays.copyOfRange(this.labels, 1, this.labels.length));
+ }
+
+ // trigger event callbacks
+ final Optional<EventStrategy> optEventStrategy = getTraversal().getStrategies().getStrategy(EventStrategy.class);
+ if (EventUtil.hasAnyCallbacks(callbackRegistry) && optEventStrategy.isPresent()) {
+ final EventStrategy es = optEventStrategy.get();
+ EventUtil.registerPropertyChange(callbackRegistry, es, element, null, null, new Object[0]);
+ }
+ }
+
+ @Override
+ public CallbackRegistry<Event.ElementPropertyChangedEvent> getMutatingCallbackRegistry() {
+ if (null == callbackRegistry) callbackRegistry = new ListCallbackRegistry<>();
+ return callbackRegistry;
+ }
+
+ @Override
+ public Set<TraverserRequirement> getRequirements() {
+ return Collections.singleton(TraverserRequirement.OBJECT);
+ }
+
+ @Override
+ public String toString() {
+ return StringFactory.stepString(this, this.labels != null ? Arrays.asList(this.labels) : this.labelTraversal);
+ }
+
+ @Override
+ public int hashCode() {
+ int result = super.hashCode();
+ if (this.labels != null) result ^= Arrays.hashCode(this.labels);
+ if (this.labelTraversal != null) result ^= this.labelTraversal.hashCode();
+ return result;
+ }
+
+ @Override
+ public List<Traversal.Admin<S, String>> getLocalChildren() {
+ return this.labelTraversal != null ? Collections.singletonList(this.labelTraversal) : Collections.emptyList();
+ }
+
+ @Override
+ public AddLabelStep<S> clone() {
+ final AddLabelStep<S> clone = (AddLabelStep<S>) super.clone();
+ if (this.labelTraversal != null)
+ clone.labelTraversal = this.labelTraversal.clone();
+ return clone;
+ }
+
+ @Override
+ public void setTraversal(final Traversal.Admin<?, ?> parentTraversal) {
+ super.setTraversal(parentTraversal);
+ if (this.labelTraversal != null)
+ this.integrateChild(this.labelTraversal);
+ }
+}
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/sideEffect/DropLabelsStep.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/sideEffect/DropLabelsStep.java
new file mode 100644
index 0000000000..14e5d0634f
--- /dev/null
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/sideEffect/DropLabelsStep.java
@@ -0,0 +1,158 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tinkerpop.gremlin.process.traversal.step.sideEffect;
+
+import org.apache.tinkerpop.gremlin.process.traversal.Traversal;
+import org.apache.tinkerpop.gremlin.process.traversal.Traverser;
+import org.apache.tinkerpop.gremlin.process.traversal.step.Mutating;
+import org.apache.tinkerpop.gremlin.process.traversal.step.TraversalParent;
+import org.apache.tinkerpop.gremlin.process.traversal.step.util.event.CallbackRegistry;
+import org.apache.tinkerpop.gremlin.process.traversal.step.util.event.Event;
+import org.apache.tinkerpop.gremlin.process.traversal.step.util.event.EventUtil;
+import org.apache.tinkerpop.gremlin.process.traversal.step.util.event.ListCallbackRegistry;
+import org.apache.tinkerpop.gremlin.process.traversal.strategy.decoration.EventStrategy;
+import org.apache.tinkerpop.gremlin.process.traversal.traverser.TraverserRequirement;
+import org.apache.tinkerpop.gremlin.process.traversal.util.TraversalUtil;
+import org.apache.tinkerpop.gremlin.structure.Element;
+import org.apache.tinkerpop.gremlin.structure.util.StringFactory;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.Optional;
+import java.util.Set;
+
+/**
+ * Side-effect step that removes labels from the current element by calling
+ * {@link Element#dropLabels()} or {@link Element#dropLabel(String, String...)}.
+ *
+ * @since 4.0.0
+ */
+public class DropLabelsStep<S extends Element> extends SideEffectStep<S>
+ implements Mutating<Event.ElementPropertyChangedEvent>, TraversalParent {
+
+ private final boolean dropAll;
+ private final String[] labels;
+ private Traversal.Admin<S, String> labelTraversal;
+ private CallbackRegistry<Event.ElementPropertyChangedEvent> callbackRegistry;
+
+ /**
+ * Constructor for dropLabels() - removes all labels.
+ */
+ public DropLabelsStep(final Traversal.Admin traversal) {
+ super(traversal);
+ this.dropAll = true;
+ this.labels = null;
+ this.labelTraversal = null;
+ }
+
+ /**
+ * Constructor for dropLabel(String, String...) - removes specific labels.
+ */
+ public DropLabelsStep(final Traversal.Admin traversal, final String label, final String... moreLabels) {
+ super(traversal);
+ this.dropAll = false;
+ final List<String> allLabels = new ArrayList<>();
+ allLabels.add(label);
+ allLabels.addAll(Arrays.asList(moreLabels));
+ this.labels = allLabels.toArray(new String[0]);
+ this.labelTraversal = null;
+ }
+
+ /**
+ * Constructor for dropLabel(Traversal) - removes dynamically computed label.
+ */
+ public DropLabelsStep(final Traversal.Admin traversal, final Traversal.Admin<S, String> labelTraversal) {
+ super(traversal);
+ this.dropAll = false;
+ this.labels = null;
+ this.labelTraversal = this.integrateChild(labelTraversal);
+ }
+
+ @Override
+ protected void sideEffect(final Traverser.Admin<S> traverser) {
+ final Element element = traverser.get();
+
+ if (this.labelTraversal != null) {
+ final String label = TraversalUtil.apply(traverser, this.labelTraversal);
+ if (label != null) {
+ element.dropLabel(label);
+ }
+ } else if (this.dropAll) {
+ element.dropLabels();
+ } else {
+ element.dropLabel(this.labels[0],
+ Arrays.copyOfRange(this.labels, 1, this.labels.length));
+ }
+
+ // trigger event callbacks
+ final Optional<EventStrategy> optEventStrategy = getTraversal().getStrategies().getStrategy(EventStrategy.class);
+ if (EventUtil.hasAnyCallbacks(callbackRegistry) && optEventStrategy.isPresent()) {
+ final EventStrategy es = optEventStrategy.get();
+ EventUtil.registerPropertyChange(callbackRegistry, es, element, null, null, new Object[0]);
+ }
+ }
+
+ @Override
+ public CallbackRegistry<Event.ElementPropertyChangedEvent> getMutatingCallbackRegistry() {
+ if (null == callbackRegistry) callbackRegistry = new ListCallbackRegistry<>();
+ return callbackRegistry;
+ }
+
+ @Override
+ public Set<TraverserRequirement> getRequirements() {
+ return Collections.singleton(TraverserRequirement.OBJECT);
+ }
+
+ @Override
+ public String toString() {
+ if (this.dropAll) return StringFactory.stepString(this);
+ return StringFactory.stepString(this, this.labels != null ? Arrays.asList(this.labels) : this.labelTraversal);
+ }
+
+ @Override
+ public int hashCode() {
+ int result = super.hashCode();
+ result ^= Boolean.hashCode(this.dropAll);
+ if (this.labels != null) result ^= Arrays.hashCode(this.labels);
+ if (this.labelTraversal != null) result ^= this.labelTraversal.hashCode();
+ return result;
+ }
+
+ @Override
+ public List<Traversal.Admin<S, String>> getLocalChildren() {
+ return this.labelTraversal != null ? Collections.singletonList(this.labelTraversal) : Collections.emptyList();
+ }
+
+ @Override
+ public DropLabelsStep<S> clone() {
+ final DropLabelsStep<S> clone = (DropLabelsStep<S>) super.clone();
+ if (this.labelTraversal != null)
+ clone.labelTraversal = this.labelTraversal.clone();
+ return clone;
+ }
+
+ @Override
+ public void setTraversal(final Traversal.Admin<?, ?> parentTraversal) {
+ super.setTraversal(parentTraversal);
+ if (this.labelTraversal != null)
+ this.integrateChild(this.labelTraversal);
+ }
+}
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/util/HasContainer.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/util/HasContainer.java
index 99a9c4e959..a6f7a39d9e 100644
--- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/util/HasContainer.java
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/util/HasContainer.java
@@ -92,7 +92,14 @@ public class HasContainer implements Serializable, Cloneable, Predicate<Element>
}
protected boolean testLabel(final Element element) {
- return this.predicate.test(element.label());
+ // Test against all labels for multi-label support.
+ // For single-label elements this is equivalent to testing element.label().
+ for (final String label : element.labels()) {
+ if (this.predicate.test(label)) {
+ return true;
+ }
+ }
+ return false;
}
protected boolean testValue(final Property property) {
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/util/WithOptions.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/util/WithOptions.java
index 2d3c940550..d9101feb97 100644
--- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/util/WithOptions.java
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/util/WithOptions.java
@@ -101,4 +101,15 @@ public class WithOptions {
* @since 4.0.0
*/
public static final String queryLanguage = "queryLanguage";
+
+ // Multi-label configuration
+ //
+
+ /**
+ * Configures multi-label behavior for valueMap and elementMap steps.
+ * When enabled, labels are returned as {@code Set<String>} instead of {@code String}.
+ *
+ * @since 4.0.0
+ */
+ public static final String multilabel = Graph.Hidden.hide("tinkerpop.multilabel");
}
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/Element.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/Element.java
index f4412123b7..9eee6e6ba0 100644
--- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/Element.java
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/Element.java
@@ -44,11 +44,28 @@ public abstract interface Element {
*/
public Object id();
+ /**
+ * Gets all labels for this element.
+ * <p>
+ * For {@link Vertex}: may return zero or more labels (multi-label support).
+ * For {@link Edge}: returns a singleton set (single label only in TinkerGraph).
+ * For {@link VertexProperty}: returns a singleton set containing the property key.
+ *
+ * @return An unmodifiable {@link Set} of labels; may be empty for vertices with no labels
+ * @since 4.0.0
+ */
+ public default Set<String> labels() {
+ return Collections.singleton(label());
+ }
+
/**
* Gets the label for the graph {@code Element} which helps categorize it.
*
* @return The label of the element
+ * @deprecated As of release 4.0.0, replaced by {@link #labels()}. This method returns an arbitrary label
+ * when multiple labels exist.
*/
+ @Deprecated
public String label();
/**
@@ -99,6 +116,41 @@ public abstract interface Element {
*/
public void remove();
+ /**
+ * Adds one or more labels to this element.
+ *
+ * @param label the first label to add
+ * @param labels additional labels to add
+ * @throws UnsupportedOperationException if the element does not support label mutation
+ * @since 4.0.0
+ */
+ public default void addLabel(final String label, final String... labels) {
+ throw Element.Exceptions.labelMutationNotSupported();
+ }
+
+ /**
+ * Removes all labels from this element, triggering the provider's default label behavior.
+ *
+ * @throws UnsupportedOperationException if the element does not support label mutation
+ * @since 4.0.0
+ */
+ public default void dropLabels() {
+ throw Element.Exceptions.labelMutationNotSupported();
+ }
+
+ /**
+ * Removes specific labels from this element.
+ * If this action removes all labels, triggers the provider's default label behavior.
+ *
+ * @param label the first label to remove
+ * @param labels additional labels to remove
+ * @throws UnsupportedOperationException if the element does not support label mutation
+ * @since 4.0.0
+ */
+ public default void dropLabel(final String label, final String... labels) {
+ throw Element.Exceptions.labelMutationNotSupported();
+ }
+
/**
* Get the values of properties as an {@link Iterator}.
@@ -145,5 +197,9 @@ public abstract interface Element {
public static IllegalArgumentException labelCanNotBeAHiddenKey(final String label) {
return new IllegalArgumentException("Label can not be a hidden key: " + label);
}
+
+ public static UnsupportedOperationException labelMutationNotSupported() {
+ return new UnsupportedOperationException("Label mutation is not supported on this element");
+ }
}
}
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/VertexProperty.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/VertexProperty.java
index 1bf76b3c54..679b13da7a 100644
--- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/VertexProperty.java
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/VertexProperty.java
@@ -21,7 +21,9 @@ package org.apache.tinkerpop.gremlin.structure;
import org.apache.tinkerpop.gremlin.process.traversal.lambda.CardinalityValueTraversal;
import org.apache.tinkerpop.gremlin.structure.util.empty.EmptyVertexProperty;
+import java.util.Collections;
import java.util.Iterator;
+import java.util.Set;
/**
* A {@code VertexProperty} is similar to a {@link Property} in that it denotes a key/value pair associated with an
@@ -78,6 +80,18 @@ public interface VertexProperty<V> extends Property<V>, Element {
return this.key();
}
+ /**
+ * Returns a singleton set containing the property key, consistent with the single-label
+ * semantics of {@link VertexProperty}.
+ *
+ * @return a singleton {@link Set} containing this property's key
+ * @since 4.0.0
+ */
+ @Override
+ public default Set<String> labels() {
+ return Collections.singleton(this.key());
+ }
+
/**
* Constructs an empty {@code VertexProperty}.
*/
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/io/binary/types/VertexSerializer.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/io/binary/types/VertexSerializer.java
index 1ab1d82ba0..ce6befecba 100644
--- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/io/binary/types/VertexSerializer.java
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/io/binary/types/VertexSerializer.java
@@ -29,7 +29,9 @@ import org.apache.tinkerpop.gremlin.structure.util.detached.DetachedVertexProper
import org.apache.tinkerpop.gremlin.structure.util.reference.ReferenceVertex;
import java.io.IOException;
+import java.util.ArrayList;
import java.util.Collections;
+import java.util.LinkedHashSet;
import java.util.List;
/**
@@ -43,11 +45,19 @@ public class VertexSerializer extends SimpleTypeSerializer<Vertex> {
@Override
protected Vertex readValue(final Buffer buffer, final GraphBinaryReader context) throws IOException {
final Object id = context.read(buffer);
- // reading single string value for now according to GraphBinaryV4
- final String label = (String) context.readValue(buffer, List.class, false).get(0);
+ // Read labels as List<String> for multi-label support
+ final List<String> labelList = context.readValue(buffer, List.class, false);
final List<DetachedVertexProperty> properties = context.read(buffer);
- final DetachedVertex.Builder builder = DetachedVertex.build().setId(id).setLabel(label);
+ final DetachedVertex.Builder builder = DetachedVertex.build().setId(id);
+
+ if (labelList != null && !labelList.isEmpty()) {
+ if (labelList.size() == 1) {
+ builder.setLabel(labelList.get(0));
+ } else {
+ builder.setLabels(new LinkedHashSet<>(labelList));
+ }
+ }
if (properties != null) {
for (final DetachedVertexProperty vp : properties) {
@@ -61,11 +71,12 @@ public class VertexSerializer extends SimpleTypeSerializer<Vertex> {
@Override
protected void writeValue(final Vertex value, final Buffer buffer, final GraphBinaryWriter context) throws IOException {
context.write(value.id(), buffer);
- // wrapping label into list here for now according to GraphBinaryV4, but we aren't allowing null label yet
- if (value.label() == null) {
- throw new IOException("Unexpected null value when nullable is false");
+ // Write all labels as List<String> for multi-label support.
+ final java.util.Set<String> labels = value.labels();
+ if (labels == null || labels.isEmpty()) {
+ throw new IOException("Unexpected null or empty labels when nullable is false");
}
- context.writeValue(Collections.singletonList(value.label()), buffer, false);
+ context.writeValue(new ArrayList<>(labels), buffer, false);
if (value instanceof ReferenceVertex) {
context.write(null, buffer);
}
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/io/graphson/GraphSONSerializersV4.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/io/graphson/GraphSONSerializersV4.java
index d68458b671..3fd6815077 100644
--- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/io/graphson/GraphSONSerializersV4.java
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/io/graphson/GraphSONSerializersV4.java
@@ -86,7 +86,7 @@ class GraphSONSerializersV4 {
jsonGenerator.writeStartObject();
jsonGenerator.writeObjectField(GraphSONTokens.ID, vertex.id());
- writeLabel(jsonGenerator, GraphSONTokens.LABEL, vertex.label());
+ writeLabels(jsonGenerator, GraphSONTokens.LABEL, vertex.labels());
writeTypeForGraphObjectIfUntyped(jsonGenerator, typeInfo, GraphSONTokens.VERTEX);
writeProperties(vertex, jsonGenerator, serializerProvider);
@@ -394,8 +394,14 @@ class GraphSONSerializersV4 {
v.setId(deserializationContext.readValue(jsonParser, Object.class));
} else if (jsonParser.getCurrentName().equals(GraphSONTokens.LABEL)) {
jsonParser.nextToken();
+ final java.util.Set<String> labels = new java.util.LinkedHashSet<>();
while (jsonParser.nextToken() != JsonToken.END_ARRAY) {
- v.setLabel(jsonParser.getText());
+ labels.add(jsonParser.getText());
+ }
+ if (labels.size() == 1) {
+ v.setLabel(labels.iterator().next());
+ } else if (!labels.isEmpty()) {
+ v.setLabels(labels);
}
} else if (jsonParser.getCurrentName().equals(GraphSONTokens.PROPERTIES)) {
jsonParser.nextToken();
@@ -692,4 +698,16 @@ class GraphSONSerializersV4 {
jsonGenerator.writeString(labelValue);
jsonGenerator.writeEndArray();
}
+
+ /**
+ * Helper method for writing multiple labels as an array. Used for multi-label vertex support.
+ */
+ private static void writeLabels(final JsonGenerator jsonGenerator, final String labelName, final java.util.Set<String> labels) throws IOException {
+ jsonGenerator.writeFieldName(labelName);
+ jsonGenerator.writeStartArray();
+ for (final String label : labels) {
+ jsonGenerator.writeString(label);
+ }
+ jsonGenerator.writeEndArray();
+ }
}
\ No newline at end of file
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/util/ElementHelper.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/util/ElementHelper.java
index 1924e6ef32..7368fe339b 100644
--- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/util/ElementHelper.java
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/util/ElementHelper.java
@@ -30,9 +30,11 @@ import org.javatuples.Pair;
import java.util.ArrayList;
import java.util.Arrays;
+import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
+import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
@@ -245,6 +247,41 @@ public final class ElementHelper {
return Optional.empty();
}
+ /**
+ * Extracts the value of the {@link T#label} key from the list of arguments as a {@link Set} of labels.
+ * Supports both single {@link String} values and {@link java.util.Collection} values for multi-label vertices.
+ *
+ * @param keyValues a list of key/value pairs
+ * @return the labels associated with {@link T#label}, or empty if not present
+ * @since 4.0.0
+ */
+ public static Optional<Set<String>> getLabelsValue(final Object... keyValues) {
+ for (int i = 0; i < keyValues.length; i = i + 2) {
+ if (keyValues[i].equals(T.label)) {
+ final Object labelValue = keyValues[i + 1];
+ if (labelValue instanceof String) {
+ ElementHelper.validateLabel((String) labelValue);
+ final Set<String> labels = new LinkedHashSet<>();
+ labels.add((String) labelValue);
+ return Optional.of(labels);
+ } else if (labelValue instanceof Collection) {
+ final Set<String> labels = new LinkedHashSet<>();
+ for (final Object l : (Collection<?>) labelValue) {
+ if (!(l instanceof String)) {
+ throw new IllegalArgumentException("T.label collection must contain only Strings");
+ }
+ ElementHelper.validateLabel((String) l);
+ labels.add((String) l);
+ }
+ return Optional.of(labels);
+ } else {
+ throw new IllegalArgumentException("T.label value must be String or Collection<String>");
+ }
+ }
+ }
+ return Optional.empty();
+ }
+
/**
* Assign key/value pairs as properties to an {@link Element}. If the value of {@link T#id} or
* {@link T#label} is in the set of pairs, then they are ignored.
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/util/detached/DetachedVertex.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/util/detached/DetachedVertex.java
index c9be9f71da..977eb8ebcc 100644
--- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/util/detached/DetachedVertex.java
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/util/detached/DetachedVertex.java
@@ -32,8 +32,10 @@ import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
+import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
+import java.util.Set;
/**
* Represents a {@link Vertex} that is disconnected from a {@link Graph}. "Disconnection" can mean detachment from
@@ -53,11 +55,24 @@ public class DetachedVertex extends DetachedElement<Vertex> implements Vertex {
private static final String VALUE = "value";
private static final String PROPERTIES = "properties";
+ private Set<String> vertexLabels;
+
private DetachedVertex() {}
protected DetachedVertex(final Vertex vertex, final boolean withProperties) {
super(vertex);
+ // Capture all labels from the source vertex for multi-label support.
+ // super(vertex) only stores element.label() (single label) in DetachedElement.
+ try {
+ final Set<String> srcLabels = vertex.labels();
+ if (srcLabels.size() > 1) {
+ this.vertexLabels = new LinkedHashSet<>(srcLabels);
+ }
+ } catch (UnsupportedOperationException e) {
+ // Adjacent vertices in graph computer context may not support labels()
+ }
+
// only serialize properties if requested, and there are meta properties present. this prevents unnecessary
// object creation of a new HashMap of a new HashMap which will just be empty. it will use
// Collections.emptyMap() by default
@@ -99,6 +114,23 @@ public class DetachedVertex extends DetachedElement<Vertex> implements Vertex {
}
}
+ @Override
+ public Set<String> labels() {
+ if (this.vertexLabels != null) {
+ return Collections.unmodifiableSet(this.vertexLabels);
+ }
+ // Fall back to single label from parent
+ return this.label != null ? Collections.singleton(this.label) : Collections.emptySet();
+ }
+
+ @Override
+ public String label() {
+ if (this.vertexLabels != null && !this.vertexLabels.isEmpty()) {
+ return this.vertexLabels.iterator().next();
+ }
+ return this.label != null ? this.label : Vertex.DEFAULT_LABEL;
+ }
+
@Override
public <V> VertexProperty<V> property(final String key, final V value) {
throw Element.Exceptions.propertyAdditionNotSupported();
@@ -196,6 +228,14 @@ public class DetachedVertex extends DetachedElement<Vertex> implements Vertex {
return this;
}
+ public Builder setLabels(final Set<String> labels) {
+ v.vertexLabels = labels != null ? new LinkedHashSet<>(labels) : null;
+ if (labels != null && !labels.isEmpty()) {
+ v.label = labels.iterator().next();
+ }
+ return this;
+ }
+
public DetachedVertex create() {
return v;
}
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/util/reference/ReferenceVertex.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/util/reference/ReferenceVertex.java
index ac50c3a6a0..a55cd4b549 100644
--- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/util/reference/ReferenceVertex.java
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/util/reference/ReferenceVertex.java
@@ -28,12 +28,16 @@ import org.apache.tinkerpop.gremlin.structure.util.StringFactory;
import java.util.Collections;
import java.util.Iterator;
+import java.util.LinkedHashSet;
+import java.util.Set;
/**
* @author Marko A. Rodriguez (http://markorodriguez.com)
*/
public class ReferenceVertex extends ReferenceElement<Vertex> implements Vertex {
+ private Set<String> vertexLabels;
+
private ReferenceVertex() {
}
@@ -46,8 +50,39 @@ public class ReferenceVertex extends ReferenceElement<Vertex> implements Vertex
super(id, label);
}
+ public ReferenceVertex(final Object id, final Set<String> labels) {
+ super(id, labels != null && !labels.isEmpty() ? labels.iterator().next() : Vertex.DEFAULT_LABEL);
+ this.vertexLabels = labels != null ? new LinkedHashSet<>(labels) : null;
+ }
+
public ReferenceVertex(final Vertex vertex) {
super(vertex);
+ // Capture all labels from the source vertex for multi-label support.
+ // super(vertex) only stores element.label() (single label) in ReferenceElement.
+ try {
+ final Set<String> srcLabels = vertex.labels();
+ if (srcLabels.size() > 1) {
+ this.vertexLabels = new LinkedHashSet<>(srcLabels);
+ }
+ } catch (UnsupportedOperationException e) {
+ // Adjacent vertices in graph computer context may not support labels()
+ }
+ }
+
+ @Override
+ public Set<String> labels() {
+ if (this.vertexLabels != null) {
+ return Collections.unmodifiableSet(this.vertexLabels);
+ }
+ return this.label != null ? Collections.singleton(this.label) : Collections.emptySet();
+ }
+
+ @Override
+ public String label() {
+ if (this.vertexLabels != null && !this.vertexLabels.isEmpty()) {
+ return this.vertexLabels.iterator().next();
+ }
+ return this.label != null ? this.label : Vertex.DEFAULT_LABEL;
}
@Override
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/util/star/StarGraph.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/util/star/StarGraph.java
index b84d1d36bb..8daaf64aef 100644
--- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/util/star/StarGraph.java
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/util/star/StarGraph.java
@@ -732,6 +732,11 @@ public final class StarGraph implements Graph, Serializable {
throw GraphComputer.Exceptions.adjacentVertexLabelsCanNotBeRead();
}
+ @Override
+ public Set<String> labels() {
+ throw GraphComputer.Exceptions.adjacentVertexLabelsCanNotBeRead();
+ }
+
@Override
public Graph graph() {
return StarGraph.this;
diff --git a/gremlin-language/src/main/antlr4/Gremlin.g4 b/gremlin-language/src/main/antlr4/Gremlin.g4
index 31205483b3..f10489dd1b 100644
--- a/gremlin-language/src/main/antlr4/Gremlin.g4
+++ b/gremlin-language/src/main/antlr4/Gremlin.g4
@@ -119,6 +119,7 @@ traversalSourceSpawnMethod_addE
traversalSourceSpawnMethod_addV
: K_ADDV LPAREN RPAREN
| K_ADDV LPAREN stringArgument RPAREN
+ | K_ADDV LPAREN stringArgument COMMA stringArgument (COMMA stringArgument)* RPAREN
| K_ADDV LPAREN nestedTraversal RPAREN
;
@@ -315,6 +316,10 @@ traversalMethod
| traversalMethod_dateAdd
| traversalMethod_dateDiff
| traversalMethod_asNumber
+ | traversalMethod_labels
+ | traversalMethod_addLabel
+ | traversalMethod_dropLabels
+ | traversalMethod_dropLabel
;
traversalMethod_V
@@ -333,6 +338,7 @@ traversalMethod_addE
traversalMethod_addV
: K_ADDV LPAREN RPAREN #traversalMethod_addV_Empty
| K_ADDV LPAREN stringArgument RPAREN #traversalMethod_addV_String
+ | K_ADDV LPAREN stringArgument COMMA stringArgument (COMMA stringArgument)* RPAREN #traversalMethod_addV_StringVarargs
| K_ADDV LPAREN nestedTraversal RPAREN #traversalMethod_addV_Traversal
;
@@ -628,6 +634,24 @@ traversalMethod_label
: K_LABEL LPAREN RPAREN
;
+traversalMethod_labels
+ : K_LABELS LPAREN RPAREN
+ ;
+
+traversalMethod_addLabel
+ : K_ADDLABEL LPAREN stringArgument (COMMA stringArgument)* RPAREN #traversalMethod_addLabel_String
+ | K_ADDLABEL LPAREN nestedTraversal RPAREN #traversalMethod_addLabel_Traversal
+ ;
+
+traversalMethod_dropLabels
+ : K_DROPLABELS LPAREN RPAREN #traversalMethod_dropLabels_Empty
+ ;
+
+traversalMethod_dropLabel
+ : K_DROPLABEL LPAREN stringArgument (COMMA stringArgument)* RPAREN #traversalMethod_dropLabel_String
+ | K_DROPLABEL LPAREN nestedTraversal RPAREN #traversalMethod_dropLabel_Traversal
+ ;
+
traversalMethod_length
: K_LENGTH LPAREN RPAREN #traversalMethod_length_Empty
| K_LENGTH LPAREN traversalScope RPAREN #traversalMethod_length_Scope
@@ -1761,6 +1785,7 @@ keyword
: TRAVERSAL_ROOT // g - __ is not an allowable key in this context
| K_ADDALL
| K_ADDE
+ | K_ADDLABEL
| K_ADDV
| K_AGGREGATE
| K_ALL
@@ -1832,6 +1857,8 @@ keyword
| K_DOUBLE
| K_DOUBLEU
| K_DROP
+ | K_DROPLABEL
+ | K_DROPLABELS
| K_DT
| K_DURATION
| K_DURATIONC
@@ -2074,6 +2101,7 @@ keyword
K_ADDALL: 'addAll';
K_ADDE: 'addE';
+K_ADDLABEL: 'addLabel';
K_ADDV: 'addV';
K_AGGREGATE: 'aggregate';
K_ALL: 'all';
@@ -2145,6 +2173,8 @@ K_DIV: 'div';
K_DOUBLE: 'double';
K_DOUBLEU: 'DOUBLE';
K_DROP: 'drop';
+K_DROPLABEL: 'dropLabel';
+K_DROPLABELS: 'dropLabels';
K_DT: 'DT';
K_DURATION: 'duration';
K_DURATIONC: 'Duration';
diff --git a/gremlin-util/src/test/java/org/apache/tinkerpop/gremlin/util/ser/binary/TypeSerializerFailureTests.java b/gremlin-util/src/test/java/org/apache/tinkerpop/gremlin/util/ser/binary/TypeSerializerFailureTests.java
index 0ff8db09cf..3a9c816a0c 100644
--- a/gremlin-util/src/test/java/org/apache/tinkerpop/gremlin/util/ser/binary/TypeSerializerFailureTests.java
+++ b/gremlin-util/src/test/java/org/apache/tinkerpop/gremlin/util/ser/binary/TypeSerializerFailureTests.java
@@ -57,7 +57,7 @@ public class TypeSerializerFailureTests {
@Parameterized.Parameters(name = "Value={0}")
public static Collection input() {
- final ReferenceVertex vertex = new ReferenceVertex("a vertex", null);
+ final ReferenceVertex vertex = new ReferenceVertex("a vertex", (String) null);
final BulkSet<Object> bulkSet = new BulkSet<>();
bulkSet.add(vertex, 1L);
diff --git a/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/AbstractTinkerGraph.java b/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/AbstractTinkerGraph.java
index 4e08872e53..a77edac34d 100644
--- a/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/AbstractTinkerGraph.java
+++ b/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/AbstractTinkerGraph.java
@@ -354,6 +354,17 @@ public abstract class AbstractTinkerGraph implements Graph {
protected abstract void addInEdge(final TinkerVertex vertex, final String label, final Edge edge);
+ /**
+ * Called when a vertex's labels are modified to allow the graph to update any internal label indices.
+ * The default implementation is a no-op since TinkerGraph does not maintain a separate label index.
+ *
+ * @param vertex the vertex whose labels have changed
+ * @since 4.0.0
+ */
+ public void updateVertexLabelIndex(final TinkerVertex vertex) {
+ // no-op by default - TinkerGraph does not maintain a separate label index
+ }
+
protected TinkerVertex createTinkerVertex(final Object id, final String label, final AbstractTinkerGraph graph) {
return new TinkerVertex(id, label, graph);
}
@@ -362,6 +373,19 @@ public abstract class AbstractTinkerGraph implements Graph {
return new TinkerVertex(id, label, graph, currentVersion);
}
+ /**
+ * Creates a TinkerVertex with multiple labels.
+ *
+ * @param id the vertex id
+ * @param labels the set of labels for the vertex
+ * @param graph the graph instance
+ * @return a new TinkerVertex
+ * @since 4.0.0
+ */
+ protected TinkerVertex createTinkerVertex(final Object id, final Set<String> labels, final AbstractTinkerGraph graph) {
+ return new TinkerVertex(id, labels, graph);
+ }
+
protected TinkerEdge createTinkerEdge(final Object id, final Vertex outVertex, final String label, final Vertex inVertex) {
return new TinkerEdge(id, outVertex, label, inVertex);
}
diff --git a/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerEdge.java b/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerEdge.java
index 49bfc7401e..3ced83454e 100644
--- a/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerEdge.java
+++ b/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerEdge.java
@@ -105,6 +105,11 @@ public class TinkerEdge extends TinkerElement implements Edge {
return null == this.properties ? Collections.emptySet() : this.properties.keySet();
}
+ @Override
+ public Set<String> labels() {
+ return Collections.singleton(this.label);
+ }
+
@Override
public void remove() {
graph.touch(this);
diff --git a/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerGraph.java b/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerGraph.java
index 4b5ceeadae..ffe328f98e 100644
--- a/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerGraph.java
+++ b/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerGraph.java
@@ -141,7 +141,8 @@ public class TinkerGraph extends AbstractTinkerGraph {
public Vertex addVertex(final Object... keyValues) {
ElementHelper.legalPropertyKeyValueArray(keyValues);
Object idValue = vertexIdManager.convert(ElementHelper.getIdValue(keyValues).orElse(null));
- final String label = ElementHelper.getLabelValue(keyValues).orElse(Vertex.DEFAULT_LABEL);
+ final Set<String> labels = ElementHelper.getLabelsValue(keyValues).orElse(
+ Collections.singleton(Vertex.DEFAULT_LABEL));
if (null != idValue) {
if (this.vertices.containsKey(idValue))
@@ -150,7 +151,7 @@ public class TinkerGraph extends AbstractTinkerGraph {
idValue = vertexIdManager.getNextId(this);
}
- final Vertex vertex = createTinkerVertex(idValue, label, this);
+ final Vertex vertex = createTinkerVertex(idValue, labels, this);
ElementHelper.attachProperties(vertex, VertexProperty.Cardinality.list, keyValues);
this.vertices.put(vertex.id(), vertex);
vertexLabelCounts.computeIfAbsent(label, l -> new AtomicInteger()).incrementAndGet();
diff --git a/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerVertex.java b/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerVertex.java
index c8498b9434..b10ebe1e7b 100644
--- a/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerVertex.java
+++ b/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerVertex.java
@@ -31,6 +31,7 @@ import org.apache.tinkerpop.gremlin.util.iterator.IteratorUtils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
+import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@@ -54,11 +55,18 @@ public class TinkerVertex extends TinkerElement implements Vertex {
private boolean allowNullPropertyValues;
private final boolean isTxMode;
+ /**
+ * Multi-label storage for this vertex. Shadows the single-label field in TinkerElement.
+ */
+ protected final Set<String> vertexLabels;
+
protected TinkerVertex(final Object id, final String label, final AbstractTinkerGraph graph) {
super(id, label);
this.graph = graph;
this.isTxMode = graph instanceof TinkerTransactionGraph;
this.allowNullPropertyValues = graph.features().vertex().supportsNullPropertyValues();
+ this.vertexLabels = ConcurrentHashMap.newKeySet();
+ this.vertexLabels.add(null == label ? Vertex.DEFAULT_LABEL : label);
}
protected TinkerVertex(final Object id, final String label, final AbstractTinkerGraph graph, final long currentVersion) {
@@ -66,12 +74,79 @@ public class TinkerVertex extends TinkerElement implements Vertex {
this.graph = graph;
this.isTxMode = graph instanceof TinkerTransactionGraph;
this.allowNullPropertyValues = graph.features().vertex().supportsNullPropertyValues();
+ this.vertexLabels = ConcurrentHashMap.newKeySet();
+ this.vertexLabels.add(null == label ? Vertex.DEFAULT_LABEL : label);
+ }
+
+ /**
+ * Constructs a TinkerVertex with multiple labels.
+ */
+ protected TinkerVertex(final Object id, final Set<String> labels, final AbstractTinkerGraph graph) {
+ super(id, (labels == null || labels.isEmpty()) ? Vertex.DEFAULT_LABEL : labels.iterator().next());
+ this.graph = graph;
+ this.isTxMode = graph instanceof TinkerTransactionGraph;
+ this.allowNullPropertyValues = graph.features().vertex().supportsNullPropertyValues();
+ if (labels == null || labels.isEmpty()) {
+ this.vertexLabels = ConcurrentHashMap.newKeySet();
+ this.vertexLabels.add(Vertex.DEFAULT_LABEL);
+ } else {
+ this.vertexLabels = ConcurrentHashMap.newKeySet();
+ this.vertexLabels.addAll(labels);
+ }
+ }
+
+ @Override
+ public Set<String> labels() {
+ return Collections.unmodifiableSet(this.vertexLabels);
+ }
+
+ @Override
+ @Deprecated
+ public String label() {
+ return this.vertexLabels.iterator().next();
+ }
+
+ @Override
+ public void addLabel(final String label, final String... labels) {
+ ElementHelper.validateLabel(label);
+ for (final String l : labels) {
+ ElementHelper.validateLabel(l);
+ }
+
+ // Remove default label if it was the only label and we're adding real labels
+ if (this.vertexLabels.size() == 1 && this.vertexLabels.contains(Vertex.DEFAULT_LABEL)) {
+ this.vertexLabels.remove(Vertex.DEFAULT_LABEL);
+ }
+
+ this.vertexLabels.add(label);
+ Collections.addAll(this.vertexLabels, labels);
+ this.graph.updateVertexLabelIndex(this);
+ }
+
+ @Override
+ public void dropLabels() {
+ this.vertexLabels.clear();
+ this.vertexLabels.add(Vertex.DEFAULT_LABEL);
+ this.graph.updateVertexLabelIndex(this);
+ }
+
+ @Override
+ public void dropLabel(final String label, final String... labels) {
+ this.vertexLabels.remove(label);
+ for (final String l : labels) {
+ this.vertexLabels.remove(l);
+ }
+
+ if (this.vertexLabels.isEmpty()) {
+ this.vertexLabels.add(Vertex.DEFAULT_LABEL);
+ }
+ this.graph.updateVertexLabelIndex(this);
}
@Override
public Object clone() {
if (!isTxMode) {
- final TinkerVertex vertex = new TinkerVertex(id, label, graph, currentVersion);
+ final TinkerVertex vertex = new TinkerVertex(id, new LinkedHashSet<>(vertexLabels), graph);
vertex.inEdgesId = inEdgesId;
vertex.outEdgesId = outEdgesId;
vertex.properties = properties;
@@ -79,6 +154,8 @@ public class TinkerVertex extends TinkerElement implements Vertex {
}
final TinkerVertex vertex = new TinkerVertex(id, label, graph, currentVersion);
+ vertex.vertexLabels.clear();
+ vertex.vertexLabels.addAll(this.vertexLabels);
if (inEdgesId != null)
vertex.inEdgesId = CollectionUtil.clone((ConcurrentHashMap<String, Set<Object>>) inEdgesId);
diff --git a/tinkergraph-gremlin/src/test/java/org/apache/tinkerpop/gremlin/tinkergraph/process/traversal/step/map/LabelsStepTest.java b/tinkergraph-gremlin/src/test/java/org/apache/tinkerpop/gremlin/tinkergraph/process/traversal/step/map/LabelsStepTest.java
new file mode 100644
index 0000000000..9c816cf9c8
--- /dev/null
+++ b/tinkergraph-gremlin/src/test/java/org/apache/tinkerpop/gremlin/tinkergraph/process/traversal/step/map/LabelsStepTest.java
@@ -0,0 +1,106 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tinkerpop.gremlin.tinkergraph.process.traversal.step.map;
+
+import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
+import org.apache.tinkerpop.gremlin.structure.Edge;
+import org.apache.tinkerpop.gremlin.structure.Graph;
+import org.apache.tinkerpop.gremlin.structure.Vertex;
+import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.containsInAnyOrder;
+import static org.hamcrest.Matchers.hasSize;
+import static org.hamcrest.Matchers.is;
+
+/**
+ * Tests for the labels() traversal step.
+ */
+public class LabelsStepTest {
+
+ private Graph graph;
+ private GraphTraversalSource g;
+
+ @Before
+ public void setup() {
+ graph = TinkerGraph.open();
+ g = graph.traversal();
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ graph.close();
+ }
+
+ @Test
+ public void shouldStreamAllLabelsFromVertex() {
+ final Vertex v = g.addV("person").addLabel("employee").next();
+ final List<String> labels = g.V(v).labels().toList();
+ assertThat(labels, hasSize(2));
+ assertThat(labels, containsInAnyOrder("person", "employee"));
+ }
+
+ @Test
+ public void shouldCountLabelsCorrectly() {
+ final Vertex v = g.addV("person").addLabel("employee").next();
+ final long count = g.V(v).labels().count().next();
+ assertThat(count, is(2L));
+ }
+
+ @Test
+ public void shouldFoldAllLabels() {
+ final Vertex v = g.addV("person").addLabel("employee").next();
+ final List<String> folded = g.V(v).labels().fold().next();
+ assertThat(folded, hasSize(2));
+ assertThat(folded, containsInAnyOrder("person", "employee"));
+ }
+
+ @Test
+ public void shouldReturnSingletonForEdge() {
+ final Vertex v1 = g.addV("person").next();
+ final Vertex v2 = g.addV("person").next();
+ final Edge e = v1.addEdge("knows", v2);
+ final List<String> labels = g.E(e).labels().toList();
+ assertThat(labels, hasSize(1));
+ assertThat(labels, containsInAnyOrder("knows"));
+ }
+
+ @Test
+ public void shouldStreamSingleLabelFromSingleLabelVertex() {
+ final Vertex v = g.addV("person").next();
+ final List<String> labels = g.V(v).labels().toList();
+ assertThat(labels, hasSize(1));
+ assertThat(labels, containsInAnyOrder("person"));
+ }
+
+ @Test
+ public void shouldStreamDefaultLabelFromDefaultVertex() {
+ final Vertex v = g.addV().next();
+ final List<String> labels = g.V(v).labels().toList();
+ assertThat(labels, hasSize(1));
+ assertThat(labels, containsInAnyOrder(Vertex.DEFAULT_LABEL));
+ }
+}
diff --git a/tinkergraph-gremlin/src/test/java/org/apache/tinkerpop/gremlin/tinkergraph/process/traversal/step/map/MergeVMultiLabelTest.java b/tinkergraph-gremlin/src/test/java/org/apache/tinkerpop/gremlin/tinkergraph/process/traversal/step/map/MergeVMultiLabelTest.java
new file mode 100644
index 0000000000..2257a15b60
--- /dev/null
+++ b/tinkergraph-gremlin/src/test/java/org/apache/tinkerpop/gremlin/tinkergraph/process/traversal/step/map/MergeVMultiLabelTest.java
@@ -0,0 +1,154 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tinkerpop.gremlin.tinkergraph.process.traversal.step.map;
+
+import org.apache.tinkerpop.gremlin.process.traversal.Merge;
+import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
+import org.apache.tinkerpop.gremlin.structure.Graph;
+import org.apache.tinkerpop.gremlin.structure.T;
+import org.apache.tinkerpop.gremlin.structure.Vertex;
+import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.containsInAnyOrder;
+import static org.hamcrest.Matchers.hasSize;
+import static org.hamcrest.Matchers.is;
+
+/**
+ * Tests for mergeV() multi-label support.
+ */
+public class MergeVMultiLabelTest {
+
+ private Graph graph;
+ private GraphTraversalSource g;
+
+ @Before
+ public void setup() {
+ graph = TinkerGraph.open();
+ g = graph.traversal();
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ graph.close();
+ }
+
+ // --- mergeV create with multi-label ---
+
+ @Test
+ public void shouldCreateVertexWithMultiLabelViaMergeV() {
+ final Set<String> labels = new LinkedHashSet<>(Arrays.asList("person", "employee"));
+ final Vertex v = g.mergeV(Map.of(T.label, labels, "name", "marko")).next();
+ assertThat(v.labels(), hasSize(2));
+ assertThat(v.labels(), containsInAnyOrder("person", "employee"));
+ assertThat(v.value("name"), is("marko"));
+ }
+
+ @Test
+ public void shouldCreateVertexWithSingleLabelViaMergeV() {
+ final Vertex v = g.mergeV(Map.of(T.label, "person", "name", "marko")).next();
+ assertThat(v.labels(), hasSize(1));
+ assertThat(v.labels(), containsInAnyOrder("person"));
+ }
+
+ @Test
+ public void shouldCreateVertexWithListLabelViaMergeV() {
+ final List<String> labels = Arrays.asList("a", "b", "c");
+ final Vertex v = g.mergeV(Map.of(T.label, labels, "name", "test")).next();
+ assertThat(v.labels(), hasSize(3));
+ assertThat(v.labels(), containsInAnyOrder("a", "b", "c"));
+ }
+
+ // --- mergeV match with multi-label ---
+
+ @Test
+ public void shouldMatchVertexWithMultiLabelViaMergeV() {
+ // create a vertex with two labels
+ final Vertex existing = g.addV("person").addLabel("employee").property("name", "marko").next();
+
+ // mergeV should match it using AND semantics
+ final Set<String> labels = new LinkedHashSet<>(Arrays.asList("person", "employee"));
+ final Vertex matched = g.mergeV(Map.of(T.label, labels, "name", "marko")).next();
+
+ assertThat(matched.id(), is(existing.id()));
+ // should not create a new vertex
+ assertThat(g.V().count().next(), is(1L));
+ }
+
+ @Test
+ public void shouldNotMatchWhenVertexMissingOneLabel() {
+ // create a vertex with only one label
+ g.addV("person").property("name", "marko").next();
+
+ // mergeV with two labels should NOT match (AND semantics)
+ final Set<String> labels = new LinkedHashSet<>(Arrays.asList("person", "employee"));
+ g.mergeV(Map.of(T.label, labels, "name", "marko")).next();
+
+ // should have created a new vertex
+ assertThat(g.V().count().next(), is(2L));
+ }
+
+ // --- mergeV onMatch label replacement ---
+
+ @Test
+ public void shouldReplaceLabelsOnMatchWithSingleLabel() {
+ final Vertex v = g.addV("person").addLabel("employee").property("name", "marko").next();
+
+ g.mergeV(Map.of(T.label, "person", "name", "marko"))
+ .option(Merge.onMatch, Map.of(T.label, "manager")).next();
+
+ // labels should be wholly replaced
+ assertThat(v.labels(), hasSize(1));
+ assertThat(v.labels(), containsInAnyOrder("manager"));
+ }
+
+ @Test
+ public void shouldReplaceLabelsOnMatchWithMultiLabel() {
+ final Vertex v = g.addV("person").property("name", "marko").next();
+
+ final Set<String> newLabels = new LinkedHashSet<>(Arrays.asList("manager", "director"));
+ g.mergeV(Map.of(T.label, "person", "name", "marko"))
+ .option(Merge.onMatch, Map.of(T.label, newLabels)).next();
+
+ assertThat(v.labels(), hasSize(2));
+ assertThat(v.labels(), containsInAnyOrder("manager", "director"));
+ }
+
+ @Test
+ public void shouldApplyDefaultLabelOnMatchWithEmptyCollection() {
+ final Vertex v = g.addV("person").property("name", "marko").next();
+
+ g.mergeV(Map.of(T.label, "person", "name", "marko"))
+ .option(Merge.onMatch, Map.of(T.label, Collections.emptySet())).next();
+
+ // empty collection triggers default label behavior
+ assertThat(v.labels(), hasSize(1));
+ assertThat(v.labels(), containsInAnyOrder(Vertex.DEFAULT_LABEL));
+ }
+}
diff --git a/tinkergraph-gremlin/src/test/java/org/apache/tinkerpop/gremlin/tinkergraph/process/traversal/step/sideEffect/LabelMutationPropertyTest.java b/tinkergraph-gremlin/src/test/java/org/apache/tinkerpop/gremlin/tinkergraph/process/traversal/step/sideEffect/LabelMutationPropertyTest.java
new file mode 100644
index 0000000000..5aeea9daa8
--- /dev/null
+++ b/tinkergraph-gremlin/src/test/java/org/apache/tinkerpop/gremlin/tinkergraph/process/traversal/step/sideEffect/LabelMutationPropertyTest.java
@@ -0,0 +1,205 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tinkerpop.gremlin.tinkergraph.process.traversal.step.sideEffect;
+
+import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
+import org.apache.tinkerpop.gremlin.process.traversal.step.util.WithOptions;
+import org.apache.tinkerpop.gremlin.structure.Graph;
+import org.apache.tinkerpop.gremlin.structure.T;
+import org.apache.tinkerpop.gremlin.structure.Vertex;
+import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Random;
+import java.util.Set;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.containsInAnyOrder;
+import static org.hamcrest.Matchers.hasSize;
+import static org.hamcrest.Matchers.instanceOf;
+import static org.hamcrest.Matchers.is;
+
+/**
+ * Property-based tests for addLabel() and dropLabel() traversal steps.
+ * Uses randomized inputs to validate universal correctness properties.
+ */
+public class LabelMutationPropertyTest {
+
+ private static final Logger logger = LoggerFactory.getLogger(LabelMutationPropertyTest.class);
+ private static final int ITERATIONS = 100;
+ private static final String LABEL_CHARS = "abcdefghijklmnopqrstuvwxyz";
+
+ private Graph graph;
+ private GraphTraversalSource g;
+ private Random random;
+
+ @Before
+ public void setup() {
+ graph = TinkerGraph.open();
+ g = graph.traversal();
+ random = new Random(42); // deterministic seed for reproducibility
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ graph.close();
+ }
+
+ private String randomLabel() {
+ final int len = 1 + random.nextInt(8);
+ final StringBuilder sb = new StringBuilder(len);
+ for (int i = 0; i < len; i++) {
+ sb.append(LABEL_CHARS.charAt(random.nextInt(LABEL_CHARS.length())));
+ }
+ return sb.toString();
+ }
+
+ private Set<String> randomLabelSet(final int minSize, final int maxSize) {
+ final int size = minSize + random.nextInt(maxSize - minSize + 1);
+ final Set<String> labels = new HashSet<>();
+ while (labels.size() < size) {
+ labels.add(randomLabel());
+ }
+ return labels;
+ }
+
+ /**
+ * Property 4: AddLabel idempotence.
+ * For any vertex and any label L, if L is already in the vertex's label set,
+ * calling addLabel(L) shall result in the label set being unchanged.
+ */
+ @Test
+ public void shouldBeIdempotentWhenAddingExistingLabel() {
+ for (int i = 0; i < ITERATIONS; i++) {
+ final Set<String> initialLabels = randomLabelSet(1, 5);
+ final Vertex v = g.addV(initialLabels.iterator().next()).next();
+ // add remaining labels
+ for (final String l : initialLabels) {
+ g.V(v).addLabel(l).iterate();
+ }
+
+ // pick a label already present
+ final List<String> labelList = new ArrayList<>(v.labels());
+ final String existingLabel = labelList.get(random.nextInt(labelList.size()));
+ final Set<String> beforeAdd = new HashSet<>(v.labels());
+
+ // add it again - should be idempotent
+ g.V(v).addLabel(existingLabel).iterate();
+ final Set<String> afterAdd = new HashSet<>(v.labels());
+
+ assertThat("Iteration " + i + ": addLabel should be idempotent for label '" + existingLabel + "'",
+ afterAdd, is(beforeAdd));
+ }
+ }
+
+ /**
+ * Property 6: DropLabels removes all labels and applies default.
+ * For any TinkerVertex with any number of labels, calling dropLabels()
+ * shall result in the vertex having only the default label "vertex".
+ */
+ @Test
+ public void shouldApplyDefaultLabelAfterDroppingAllLabels() {
+ for (int i = 0; i < ITERATIONS; i++) {
+ final Set<String> initialLabels = randomLabelSet(1, 5);
+ final Vertex v = g.addV(initialLabels.iterator().next()).next();
+ for (final String l : initialLabels) {
+ g.V(v).addLabel(l).iterate();
+ }
+
+ // drop all labels
+ g.V(v).dropLabels().iterate();
+
+ assertThat("Iteration " + i + ": after dropLabels(), vertex should have exactly one label",
+ v.labels(), hasSize(1));
+ assertThat("Iteration " + i + ": after dropLabels(), vertex should have default label",
+ v.labels(), containsInAnyOrder(Vertex.DEFAULT_LABEL));
+ }
+ }
+
+ /**
+ * Property 8: DropLabel non-existent labels no-op.
+ * For any vertex and any label L not present in the vertex's label set,
+ * calling dropLabel(L) shall leave the label set unchanged.
+ */
+ @Test
+ public void shouldBeNoOpWhenDroppingNonExistentLabel() {
+ for (int i = 0; i < ITERATIONS; i++) {
+ final Set<String> initialLabels = randomLabelSet(1, 5);
+ final Vertex v = g.addV(initialLabels.iterator().next()).next();
+ for (final String l : initialLabels) {
+ g.V(v).addLabel(l).iterate();
+ }
+
+ // generate a label guaranteed not to be in the set
+ String nonExistent = randomLabel();
+ while (v.labels().contains(nonExistent)) {
+ nonExistent = randomLabel();
+ }
+
+ final Set<String> beforeDrop = new HashSet<>(v.labels());
+ g.V(v).dropLabel(nonExistent).iterate();
+ final Set<String> afterDrop = new HashSet<>(v.labels());
+
+ assertThat("Iteration " + i + ": dropLabel of non-existent label '" + nonExistent + "' should be no-op",
+ afterDrop, is(beforeDrop));
+ }
+ }
+
+ /**
+ * Property 12: ValueMap/ElementMap multilabel configuration.
+ * For any element with labels L, valueMap(true).with(WithOptions.multilabel) shall return
+ * labels as Set<String> equal to L, and without the config shall return a single String from L.
+ */
+ @SuppressWarnings("unchecked")
+ @Test
+ public void shouldReturnCorrectLabelTypeBasedOnMultilabelConfig() {
+ for (int i = 0; i < ITERATIONS; i++) {
+ final Set<String> initialLabels = randomLabelSet(1, 4);
+ final Vertex v = g.addV(initialLabels.iterator().next()).next();
+ for (final String l : initialLabels) {
+ g.V(v).addLabel(l).iterate();
+ }
+
+ // with multilabel config: should return Set<String>
+ final Map<Object, Object> mapWithConfig = g.V(v).valueMap(true)
+ .with(WithOptions.multilabel).next();
+ final Object labelWithConfig = mapWithConfig.get(T.label);
+ assertThat("Iteration " + i + ": with multilabel config, label should be a Set",
+ labelWithConfig, instanceOf(Set.class));
+ assertThat("Iteration " + i + ": with multilabel config, labels should match",
+ (Set<String>) labelWithConfig, is(v.labels()));
+
+ // without multilabel config: should return single String
+ final Map<Object, Object> mapWithoutConfig = g.V(v).valueMap(true).next();
+ final Object labelWithoutConfig = mapWithoutConfig.get(T.label);
+ assertThat("Iteration " + i + ": without multilabel config, label should be a String",
+ labelWithoutConfig, instanceOf(String.class));
+ assertThat("Iteration " + i + ": without multilabel config, label should be in vertex labels",
+ v.labels().contains((String) labelWithoutConfig), is(true));
+ }
+ }
+}
diff --git a/tinkergraph-gremlin/src/test/java/org/apache/tinkerpop/gremlin/tinkergraph/process/traversal/step/sideEffect/LabelMutationStepTest.java b/tinkergraph-gremlin/src/test/java/org/apache/tinkerpop/gremlin/tinkergraph/process/traversal/step/sideEffect/LabelMutationStepTest.java
new file mode 100644
index 0000000000..58ff4fbce1
--- /dev/null
+++ b/tinkergraph-gremlin/src/test/java/org/apache/tinkerpop/gremlin/tinkergraph/process/traversal/step/sideEffect/LabelMutationStepTest.java
@@ -0,0 +1,245 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tinkerpop.gremlin.tinkergraph.process.traversal.step.sideEffect;
+
+import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
+import org.apache.tinkerpop.gremlin.process.traversal.step.util.WithOptions;
+import org.apache.tinkerpop.gremlin.structure.Edge;
+import org.apache.tinkerpop.gremlin.structure.Graph;
+import org.apache.tinkerpop.gremlin.structure.T;
+import org.apache.tinkerpop.gremlin.structure.Vertex;
+import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import static org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__.constant;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.containsInAnyOrder;
+import static org.hamcrest.Matchers.hasSize;
+import static org.hamcrest.Matchers.instanceOf;
+import static org.hamcrest.Matchers.is;
+
+/**
+ * Tests for addLabel() and dropLabel() traversal steps, addV multi-label,
+ * and valueMap/elementMap multilabel configuration.
+ */
+public class LabelMutationStepTest {
+
+ private Graph graph;
+ private GraphTraversalSource g;
+
+ @Before
+ public void setup() {
+ graph = TinkerGraph.open();
+ g = graph.traversal();
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ graph.close();
+ }
+
+ // --- addLabel step tests ---
+
+ @Test
+ public void shouldAddLabelViaTraversal() {
+ final Vertex v = g.addV("person").next();
+ g.V(v).addLabel("employee").iterate();
+ assertThat(v.labels(), hasSize(2));
+ assertThat(v.labels(), containsInAnyOrder("person", "employee"));
+ }
+
+ @Test
+ public void shouldAddLabelWithConstantTraversal() {
+ final Vertex v = g.addV("person").next();
+ g.V(v).addLabel(constant("manager")).iterate();
+ assertThat(v.labels(), hasSize(2));
+ assertThat(v.labels(), containsInAnyOrder("person", "manager"));
+ }
+
+ @Test(expected = UnsupportedOperationException.class)
+ public void shouldThrowWhenAddingLabelToEdgeViaTraversal() {
+ final Vertex v1 = g.addV("person").next();
+ final Vertex v2 = g.addV("person").next();
+ v1.addEdge("knows", v2);
+ g.E().addLabel("friend").iterate();
+ }
+
+ // --- dropLabel step tests ---
+
+ @Test
+ public void shouldDropSpecificLabelViaTraversal() {
+ final Vertex v = g.addV("person").addLabel("employee").next();
+ g.V(v).dropLabel("person").iterate();
+ assertThat(v.labels(), hasSize(1));
+ assertThat(v.labels(), containsInAnyOrder("employee"));
+ }
+
+ @Test
+ public void shouldDropAllLabelsViaTraversal() {
+ final Vertex v = g.addV("person").addLabel("employee").next();
+ g.V(v).dropLabels().iterate();
+ assertThat(v.labels(), hasSize(1));
+ assertThat(v.labels(), containsInAnyOrder(Vertex.DEFAULT_LABEL));
+ }
+
+ @Test
+ public void shouldDropLabelWithConstantTraversal() {
+ final Vertex v = g.addV("person").addLabel("employee").next();
+ g.V(v).dropLabel(constant("person")).iterate();
+ assertThat(v.labels(), hasSize(1));
+ assertThat(v.labels(), containsInAnyOrder("employee"));
+ }
+
+ @Test(expected = UnsupportedOperationException.class)
+ public void shouldThrowWhenDroppingLabelsOnEdgeViaTraversal() {
+ final Vertex v1 = g.addV("person").next();
+ final Vertex v2 = g.addV("person").next();
+ v1.addEdge("knows", v2);
+ g.E().dropLabels().iterate();
+ }
+
+ // --- addV multi-label tests ---
+
+ @Test
+ public void shouldCreateVertexWithMultipleLabelsViaAddV() {
+ final Vertex v = g.addV("a").addLabel("b").next();
+ assertThat(v.labels(), hasSize(2));
+ assertThat(v.labels(), containsInAnyOrder("a", "b"));
+ }
+
+ @Test
+ public void shouldCreateVertexWithDefaultLabelViaAddV() {
+ final Vertex v = g.addV().next();
+ assertThat(v.labels(), hasSize(1));
+ assertThat(v.labels(), containsInAnyOrder(Vertex.DEFAULT_LABEL));
+ }
+
+ // --- hasLabel index consistency tests ---
+
+ @Test
+ public void shouldFindVertexByLabelAfterAddLabel() {
+ final Vertex v = g.addV("person").next();
+ g.V(v).addLabel("employee").iterate();
+ final List<Vertex> found = g.V().hasLabel("employee").toList();
+ assertThat(found, hasSize(1));
+ assertThat(found.get(0).id(), is(v.id()));
+ }
+
+ @Test
+ public void shouldNotFindVertexByLabelAfterDropLabel() {
+ final Vertex v = g.addV("person").addLabel("employee").next();
+ g.V(v).dropLabel("employee").iterate();
+ final List<Vertex> found = g.V().hasLabel("employee").toList();
+ assertThat(found, hasSize(0));
+ }
+
+ @Test
+ public void shouldFindVertexByBothLabelsWithChainedHasLabel() {
+ final Vertex v = g.addV("person").addLabel("employee").next();
+ final List<Vertex> found = g.V().hasLabel("person").hasLabel("employee").toList();
+ assertThat(found, hasSize(1));
+ assertThat(found.get(0).id(), is(v.id()));
+ }
+
+ @Test
+ public void shouldNotFindVertexMissingOneOfChainedHasLabels() {
+ final Vertex v = g.addV("person").next();
+ final List<Vertex> found = g.V().hasLabel("person").hasLabel("employee").toList();
+ assertThat(found, hasSize(0));
+ }
+
+ // --- valueMap/elementMap multilabel config tests ---
+
+ @SuppressWarnings("unchecked")
+ @Test
+ public void shouldReturnLabelsAsSetWithMultilabelConfig() {
+ final Vertex v = g.addV("person").addLabel("employee").next();
+ final Map<Object, Object> map = g.V(v).valueMap(true)
+ .with(WithOptions.multilabel).next();
+ final Object labelValue = map.get(T.label);
+ assertThat(labelValue, instanceOf(Set.class));
+ final Set<String> labels = (Set<String>) labelValue;
+ assertThat(labels, containsInAnyOrder("person", "employee"));
+ }
+
+ @SuppressWarnings("deprecation")
+ @Test
+ public void shouldReturnLabelAsSingleStringWithoutMultilabelConfig() {
+ final Vertex v = g.addV("person").next();
+ final Map<Object, Object> map = g.V(v).valueMap(true).next();
+ final Object labelValue = map.get(T.label);
+ assertThat(labelValue, instanceOf(String.class));
+ assertThat((String) labelValue, is("person"));
+ }
+
+ // --- addLabel pass-through (chaining) test ---
+
+ @Test
+ public void shouldReturnSameVertexAfterAddLabel() {
+ final Vertex v = g.addV("person").next();
+ final Vertex result = g.V(v).addLabel("employee").next();
+ assertThat(result.id(), is(v.id()));
+ assertThat(result.labels(), containsInAnyOrder("person", "employee"));
+ }
+
+ // --- dropLabel pass-through (chaining) test ---
+
+ @Test
+ public void shouldReturnSameVertexAfterDropLabel() {
+ final Vertex v = g.addV("person").addLabel("employee").next();
+ final Vertex result = g.V(v).dropLabel("employee").next();
+ assertThat(result.id(), is(v.id()));
+ }
+
+ // --- elementMap multilabel config test ---
+
+ @SuppressWarnings("unchecked")
+ @Test
+ public void shouldReturnLabelsAsSetWithElementMapMultilabelConfig() {
+ final Vertex v = g.addV("person").addLabel("employee").next();
+ final Map<Object, Object> map = g.V(v).elementMap()
+ .with(WithOptions.multilabel).next();
+ final Object labelValue = map.get(T.label);
+ assertThat(labelValue, instanceOf(Set.class));
+ final Set<String> labels = (Set<String>) labelValue;
+ assertThat(labels, containsInAnyOrder("person", "employee"));
+ }
+
+ // --- GraphTraversalSource multi-label addV test ---
+
+ @Test
+ public void shouldCreateVertexWithMultipleLabelsFromSource() {
+ final Vertex v = g.addV("person", "employee").next();
+ assertThat(v.labels(), hasSize(2));
+ assertThat(v.labels(), containsInAnyOrder("person", "employee"));
+ }
+
+ @Test
+ public void shouldCreateVertexWithThreeLabelsFromSource() {
+ final Vertex v = g.addV("person", "employee", "manager").next();
+ assertThat(v.labels(), hasSize(3));
+ assertThat(v.labels(), containsInAnyOrder("person", "employee", "manager"));
+ }
+}
diff --git a/tinkergraph-gremlin/src/test/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerVertexMultiLabelGremlinLangTest.java b/tinkergraph-gremlin/src/test/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerVertexMultiLabelGremlinLangTest.java
new file mode 100644
index 0000000000..99d373bcdd
--- /dev/null
+++ b/tinkergraph-gremlin/src/test/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerVertexMultiLabelGremlinLangTest.java
@@ -0,0 +1,121 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tinkerpop.gremlin.tinkergraph.structure;
+
+import org.apache.tinkerpop.gremlin.process.remote.EmbeddedRemoteConnection;
+import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
+import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
+import org.apache.tinkerpop.gremlin.structure.Graph;
+import org.apache.tinkerpop.gremlin.structure.Vertex;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.util.List;
+
+import static org.apache.tinkerpop.gremlin.process.traversal.AnonymousTraversalSource.traversal;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.containsInAnyOrder;
+import static org.hamcrest.Matchers.hasSize;
+import static org.hamcrest.Matchers.is;
+import static org.hamcrest.Matchers.not;
+import static org.hamcrest.Matchers.containsString;
+
+/**
+ * Tests that verify GremlinLang output for multi-label addV does not double-record
+ * addLabel steps, and that the EmbeddedRemoteConnection path works correctly.
+ */
+public class TinkerVertexMultiLabelGremlinLangTest {
+
+ private Graph graph;
+ private GraphTraversalSource g;
+
+ @Before
+ public void setup() {
+ graph = TinkerGraph.open();
+ g = graph.traversal();
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ graph.close();
+ }
+
+ @Test
+ public void shouldNotDoubleRecordAddLabelInGremlinLangFromSource() {
+ final GraphTraversal<Vertex, Vertex> t = g.addV("a", "b");
+ final String gremlinLang = t.asAdmin().getGremlinLang().getGremlin();
+ // Should contain addV("a","b") but NOT a trailing addLabel
+ assertThat(gremlinLang, not(containsString("addLabel")));
+ }
+
+ @Test
+ public void shouldNotDoubleRecordAddLabelInGremlinLangFromTraversal() {
+ final GraphTraversal<Vertex, Vertex> t = g.V().addV("a", "b");
+ final String gremlinLang = t.asAdmin().getGremlinLang().getGremlin();
+ // Should contain addV("a","b") but NOT a trailing addLabel
+ assertThat(gremlinLang, not(containsString("addLabel")));
+ }
+
+ @Test
+ public void shouldNotDoubleRecordAddLabelWithThreeLabelsFromSource() {
+ final GraphTraversal<Vertex, Vertex> t = g.addV("a", "b", "c");
+ final String gremlinLang = t.asAdmin().getGremlinLang().getGremlin();
+ assertThat(gremlinLang, not(containsString("addLabel")));
+ }
+
+ @Test
+ public void shouldCreateExactlyOneVertexViaEmbeddedRemoteConnection() throws Exception {
+ final GraphTraversalSource remoteG = traversal().with(new EmbeddedRemoteConnection(g));
+ try {
+ final List<Vertex> vertices = remoteG.addV("a", "b").toList();
+ assertThat(vertices, hasSize(1));
+ assertThat(vertices.get(0).labels(), hasSize(2));
+ assertThat(vertices.get(0).labels(), containsInAnyOrder("a", "b"));
+ } finally {
+ remoteG.close();
+ }
+ }
+
+ @Test
+ public void shouldCreateExactlyOneVertexWithThreeLabelsViaEmbeddedRemote() throws Exception {
+ final GraphTraversalSource remoteG = traversal().with(new EmbeddedRemoteConnection(g));
+ try {
+ final List<Vertex> vertices = remoteG.addV("x", "y", "z").toList();
+ assertThat(vertices, hasSize(1));
+ assertThat(vertices.get(0).labels(), hasSize(3));
+ assertThat(vertices.get(0).labels(), containsInAnyOrder("x", "y", "z"));
+ } finally {
+ remoteG.close();
+ }
+ }
+
+ @Test
+ public void shouldNotDuplicateVerticesOnRepeatedEmbeddedRemoteCalls() throws Exception {
+ final GraphTraversalSource remoteG = traversal().with(new EmbeddedRemoteConnection(g));
+ try {
+ remoteG.addV("a", "b").iterate();
+ remoteG.addV("a", "b").iterate();
+ final long count = g.V().count().next();
+ assertThat(count, is(2L));
+ } finally {
+ remoteG.close();
+ }
+ }
+}
diff --git a/tinkergraph-gremlin/src/test/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerVertexMultiLabelTest.java b/tinkergraph-gremlin/src/test/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerVertexMultiLabelTest.java
new file mode 100644
index 0000000000..5fc84f8de2
--- /dev/null
+++ b/tinkergraph-gremlin/src/test/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerVertexMultiLabelTest.java
@@ -0,0 +1,191 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tinkerpop.gremlin.tinkergraph.structure;
+
+import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
+import org.apache.tinkerpop.gremlin.structure.Edge;
+import org.apache.tinkerpop.gremlin.structure.Graph;
+import org.apache.tinkerpop.gremlin.structure.Vertex;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.util.Set;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.containsInAnyOrder;
+import static org.hamcrest.Matchers.hasSize;
+import static org.hamcrest.Matchers.is;
+
+/**
+ * Tests for multi-label support on TinkerVertex.
+ */
+public class TinkerVertexMultiLabelTest {
+
+ private Graph graph;
+ private GraphTraversalSource g;
+
+ @Before
+ public void setup() {
+ graph = TinkerGraph.open();
+ g = graph.traversal();
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ graph.close();
+ }
+
+ @Test
+ public void shouldCreateVertexWithSingleLabel() {
+ final Vertex v = g.addV("person").next();
+ assertThat(v.labels(), hasSize(1));
+ assertThat(v.labels(), containsInAnyOrder("person"));
+ }
+
+ @Test
+ public void shouldCreateVertexWithMultipleLabels() {
+ final Vertex v = g.addV("person").addLabel("employee").next();
+ assertThat(v.labels(), hasSize(2));
+ assertThat(v.labels(), containsInAnyOrder("person", "employee"));
+ }
+
+ @Test
+ public void shouldCreateVertexWithDefaultLabelWhenNoneSpecified() {
+ final Vertex v = g.addV().next();
+ assertThat(v.labels(), hasSize(1));
+ assertThat(v.labels(), containsInAnyOrder(Vertex.DEFAULT_LABEL));
+ }
+
+ @SuppressWarnings("deprecation")
+ @Test
+ public void shouldReturnFirstLabelFromDeprecatedLabelMethod() {
+ final Vertex v = g.addV("person").next();
+ assertThat(v.label(), is("person"));
+ assertThat(v.labels().contains(v.label()), is(true));
+ }
+
+ @Test(expected = UnsupportedOperationException.class)
+ public void shouldReturnUnmodifiableSetFromLabels() {
+ final Vertex v = g.addV("person").next();
+ v.labels().add("hacker");
+ }
+
+ @Test
+ public void shouldAddLabelToExistingVertex() {
+ final Vertex v = g.addV("person").next();
+ v.addLabel("employee");
+ assertThat(v.labels(), hasSize(2));
+ assertThat(v.labels(), containsInAnyOrder("person", "employee"));
+ }
+
+ @Test
+ public void shouldBeIdempotentWhenAddingExistingLabel() {
+ final Vertex v = g.addV("person").next();
+ v.addLabel("person");
+ assertThat(v.labels(), hasSize(1));
+ assertThat(v.labels(), containsInAnyOrder("person"));
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void shouldThrowWhenAddingNullLabel() {
+ final Vertex v = g.addV("person").next();
+ v.addLabel(null);
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void shouldThrowWhenAddingEmptyLabel() {
+ final Vertex v = g.addV("person").next();
+ v.addLabel("");
+ }
+
+ @Test
+ public void shouldDropAllLabelsAndAssignDefault() {
+ final Vertex v = g.addV("person").addLabel("employee").next();
+ v.dropLabels();
+ assertThat(v.labels(), hasSize(1));
+ assertThat(v.labels(), containsInAnyOrder(Vertex.DEFAULT_LABEL));
+ }
+
+ @Test
+ public void shouldDropSpecificLabel() {
+ final Vertex v = g.addV("person").addLabel("employee").next();
+ v.dropLabel("person");
+ assertThat(v.labels(), hasSize(1));
+ assertThat(v.labels(), containsInAnyOrder("employee"));
+ }
+
+ @Test
+ public void shouldBeNoOpWhenDroppingNonExistentLabel() {
+ final Vertex v = g.addV("person").next();
+ final Set<String> before = Set.copyOf(v.labels());
+ v.dropLabel("nonexistent");
+ assertThat(v.labels(), is(before));
+ }
+
+ @Test
+ public void shouldAssignDefaultWhenDroppingLastSpecificLabel() {
+ final Vertex v = g.addV("person").next();
+ v.dropLabel("person");
+ assertThat(v.labels(), hasSize(1));
+ assertThat(v.labels(), containsInAnyOrder(Vertex.DEFAULT_LABEL));
+ }
+
+ @Test(expected = UnsupportedOperationException.class)
+ public void shouldThrowWhenAddingLabelToEdge() {
+ final Vertex v1 = g.addV("person").next();
+ final Vertex v2 = g.addV("person").next();
+ final Edge e = v1.addEdge("knows", v2);
+ e.addLabel("friend");
+ }
+
+ @Test(expected = UnsupportedOperationException.class)
+ public void shouldThrowWhenDroppingLabelsOnEdge() {
+ final Vertex v1 = g.addV("person").next();
+ final Vertex v2 = g.addV("person").next();
+ final Edge e = v1.addEdge("knows", v2);
+ e.dropLabels();
+ }
+
+ @Test
+ public void shouldReturnSingletonSetForEdgeLabels() {
+ final Vertex v1 = g.addV("person").next();
+ final Vertex v2 = g.addV("person").next();
+ final Edge e = v1.addEdge("knows", v2);
+ assertThat(e.labels(), hasSize(1));
+ assertThat(e.labels(), containsInAnyOrder("knows"));
+ }
+
+ @Test
+ public void shouldRemoveDefaultLabelWhenAddingFirstRealLabel() {
+ final Vertex v = g.addV().next();
+ assertThat(v.labels(), containsInAnyOrder(Vertex.DEFAULT_LABEL));
+ v.addLabel("person");
+ assertThat(v.labels(), hasSize(1));
+ assertThat(v.labels(), containsInAnyOrder("person"));
+ }
+
+ @Test
+ public void shouldDeduplicateLabelsOnAddV() {
+ final Vertex v = g.addV("person").addLabel("person").next();
+ // addLabel("person") on a vertex already labeled "person" is idempotent
+ assertThat(v.labels(), hasSize(1));
+ assertThat(v.labels(), containsInAnyOrder("person"));
+ }
+}
(tinkerpop) 02/05: Extend multi-label to edges, fix transactions, add feature tests
Posted by xi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
xiazcy pushed a commit to branch multi-label-experiment
in repository https://gitbox.apache.org/repos/asf/tinkerpop.git
commit 511dcd9e47abda40675631488f03f41fadc84f61
Author: Yang Xia <xi...@gmail.com>
AuthorDate: Thu Jun 25 02:18:23 2026 -0700
Extend multi-label to edges, fix transactions, add feature tests
- Implement multi-label for edges with binary and GraphSON support
- Fix multi-label in TinkerTransactionGraph
- Add Gherkin feature tests for labels(), addLabel(), dropLabel() steps
- Add event/mutation support for label changes
- Thread-safe label storage for edges (ConcurrentHashMap.newKeySet())
- Wire up GLV test infrastructure for multi-label scenarios
---
AGENTS.md | 31 +
.../grammar/DefaultGremlinBaseVisitor.java | 8 +
.../language/grammar/TraversalMethodVisitor.java | 28 +
.../grammar/TraversalSourceSpawnMethodVisitor.java | 27 +-
.../traversal/dsl/graph/GraphTraversal.java | 35 +-
.../traversal/dsl/graph/GraphTraversalSource.java | 52 +-
.../gremlin/process/traversal/dsl/graph/__.java | 7 +
.../step/map/AbstractAddEdgeStepPlaceholder.java | 5 +
.../map/AbstractAddElementStepPlaceholder.java | 7 +-
.../step/map/AbstractAddVertexStepPlaceholder.java | 6 +
.../traversal/step/map/AddEdgeStartStep.java | 32 +-
.../step/map/AddEdgeStartStepPlaceholder.java | 10 +-
.../process/traversal/step/map/AddEdgeStep.java | 32 +-
.../traversal/step/map/AddEdgeStepPlaceholder.java | 10 +-
.../traversal/step/map/AddVertexStartStep.java | 11 +
.../step/map/AddVertexStartStepPlaceholder.java | 10 +-
.../process/traversal/step/map/AddVertexStep.java | 11 +
.../step/map/AddVertexStepPlaceholder.java | 10 +-
.../process/traversal/step/map/ElementMapStep.java | 6 +-
.../process/traversal/step/map/MergeEdgeStep.java | 113 ++-
.../traversal/step/map/PropertyMapStep.java | 6 +-
.../traversal/step/sideEffect/AddLabelStep.java | 18 +-
.../traversal/step/sideEffect/DropLabelsStep.java | 18 +-
.../process/traversal/step/util/WithOptions.java | 18 +
.../process/traversal/step/util/event/Event.java | 26 +
.../traversal/step/util/event/EventUtil.java | 20 +
.../structure/io/binary/types/EdgeSerializer.java | 63 +-
.../io/graphson/GraphSONSerializersV4.java | 12 +-
.../structure/util/detached/DetachedEdge.java | 34 +
.../structure/util/reference/ReferenceEdge.java | 31 +
.../gremlin/structure/util/star/StarGraph.java | 63 +-
.../Gherkin/GherkinTestRunner.cs | 6 +
.../Gherkin/IgnoreException.cs | 7 +-
gremlin-go/driver/cucumber/cucumberSteps_test.go | 1 +
.../gremlin-javascript/test/cucumber/world.js | 4 +
gremlin-language/src/main/antlr4/Gremlin.g4 | 8 +-
.../src/main/python/tests/feature/feature_steps.py | 4 +
.../gremlin/language/translator/translations.json | 878 +++++++++++++++++++++
.../gremlin/test/features/map/AddVertex.feature | 25 +-
.../gremlin/test/features/map/Labels.feature | 110 +++
.../gremlin/test/features/map/MergeVertex.feature | 124 +++
.../test/features/sideEffect/AddLabel.feature | 66 ++
.../test/features/sideEffect/DropLabel.feature | 83 ++
.../gremlin/structure/ExceptionCoverageTest.java | 3 +
.../tinkergraph/structure/AbstractTinkerGraph.java | 20 +
.../gremlin/tinkergraph/structure/TinkerEdge.java | 89 ++-
.../tinkergraph/structure/TinkerElement.java | 2 +-
.../gremlin/tinkergraph/structure/TinkerGraph.java | 30 +
.../structure/TinkerTransactionGraph.java | 39 +-
.../tinkergraph/structure/TinkerVertex.java | 33 +-
.../step/sideEffect/LabelMutationStepTest.java | 16 +-
.../structure/TinkerVertexMultiLabelTest.java | 12 +-
52 files changed, 2193 insertions(+), 127 deletions(-)
diff --git a/AGENTS.md b/AGENTS.md
index f4952c7666..f03a28338a 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -97,3 +97,34 @@ These rules apply to any AI/IDE assistant operating on this repository.
1. Prefer no change over an unsafe or speculative change.
2. Ask for clarification.
+
+## Beads Issue Tracker
+
+This project uses **bd (beads)** for issue tracking. Run `bd prime` to see full workflow context and commands.
+
+### Quick Reference
+
+```bash
+bd ready # Find available work
+bd show <id> # View issue details
+bd update <id> --claim # Claim work
+bd close <id> # Complete work
+```
+
+### Rules
+
+- Use `bd` for ALL task tracking — do NOT use TodoWrite, TaskCreate, or markdown TODO lists
+- Run `bd prime` for detailed command reference and session close protocol
+- Use `bd remember` for persistent knowledge — do NOT use MEMORY.md files
+
+**Architecture in one line:** issues live in a local Dolt DB; sync uses `refs/dolt/data` on your git remote; `.beads/issues.jsonl` is a passive export. See https://github.com/gastownhall/beads/blob/main/docs/SYNC_CONCEPTS.md for details and anti-patterns.
+
+## Session Completion
+
+**When ending a work session**, you MUST complete ALL steps below.
+
+**MANDATORY WORKFLOW:**
+
+1. **File issues for remaining work** - Create issues for anything that needs follow-up
+2. **Run quality gates** (if code changed) - Tests, linters, builds
+3. **Update issue status** - Close finished work, update in-progress items
\ No newline at end of file
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/language/grammar/DefaultGremlinBaseVisitor.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/language/grammar/DefaultGremlinBaseVisitor.java
index 10a35ec518..02fa82e925 100644
--- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/language/grammar/DefaultGremlinBaseVisitor.java
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/language/grammar/DefaultGremlinBaseVisitor.java
@@ -167,6 +167,14 @@ public class DefaultGremlinBaseVisitor<T> extends AbstractParseTreeVisitor<T> im
* {@inheritDoc}
*/
@Override public T visitTraversalMethod_addE_String(final GremlinParser.TraversalMethod_addE_StringContext ctx) { notImplemented(ctx); return null; }
+ /**
+ * {@inheritDoc}
+ */
+ @Override public T visitTraversalMethod_addE_StringVarargs(final GremlinParser.TraversalMethod_addE_StringVarargsContext ctx) { notImplemented(ctx); return null; }
+ /**
+ * {@inheritDoc}
+ */
+ @Override public T visitTraversalMethod_addE_Empty(final GremlinParser.TraversalMethod_addE_EmptyContext ctx) { notImplemented(ctx); return null; }
/**
* {@inheritDoc}
*/
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/language/grammar/TraversalMethodVisitor.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/language/grammar/TraversalMethodVisitor.java
index 216af370b4..f99ce7f4b8 100644
--- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/language/grammar/TraversalMethodVisitor.java
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/language/grammar/TraversalMethodVisitor.java
@@ -30,6 +30,7 @@ import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
import org.apache.tinkerpop.gremlin.process.traversal.step.GValue;
import org.apache.tinkerpop.gremlin.structure.Column;
import org.apache.tinkerpop.gremlin.structure.Direction;
+import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.VertexProperty.Cardinality;
@@ -204,6 +205,33 @@ public class TraversalMethodVisitor extends TraversalRootVisitor<GraphTraversal>
}
}
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public GraphTraversal visitTraversalMethod_addE_StringVarargs(final GremlinParser.TraversalMethod_addE_StringVarargsContext ctx) {
+ final List<GremlinParser.StringArgumentContext> args = ctx.stringArgument();
+ final Object firstLiteralOrVar = antlr.argumentVisitor.visitStringArgument(args.get(0));
+ final String firstLabel = firstLiteralOrVar instanceof String ? (String) firstLiteralOrVar : ((GValue<String>) firstLiteralOrVar).get();
+ final Object secondLiteralOrVar = antlr.argumentVisitor.visitStringArgument(args.get(1));
+ final String secondLabel = secondLiteralOrVar instanceof String ? (String) secondLiteralOrVar : ((GValue<String>) secondLiteralOrVar).get();
+
+ final String[] moreLabels = new String[args.size() - 2];
+ for (int i = 2; i < args.size(); i++) {
+ final Object literalOrVar = antlr.argumentVisitor.visitStringArgument(args.get(i));
+ moreLabels[i - 2] = literalOrVar instanceof String ? (String) literalOrVar : ((GValue<String>) literalOrVar).get();
+ }
+ return this.graphTraversal.addE(firstLabel, secondLabel, moreLabels);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public GraphTraversal visitTraversalMethod_addE_Empty(final GremlinParser.TraversalMethod_addE_EmptyContext ctx) {
+ return this.graphTraversal.addE(Edge.DEFAULT_LABEL);
+ }
+
/**
* {@inheritDoc}
*/
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/language/grammar/TraversalSourceSpawnMethodVisitor.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/language/grammar/TraversalSourceSpawnMethodVisitor.java
index 9ac0e9a3fe..c07c1b21b9 100644
--- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/language/grammar/TraversalSourceSpawnMethodVisitor.java
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/language/grammar/TraversalSourceSpawnMethodVisitor.java
@@ -57,17 +57,32 @@ public class TraversalSourceSpawnMethodVisitor extends DefaultGremlinBaseVisitor
*/
@Override
public GraphTraversal visitTraversalSourceSpawnMethod_addE(final GremlinParser.TraversalSourceSpawnMethod_addEContext ctx) {
- if (ctx.stringArgument() != null) {
- final Object literalOrVar = antlr.argumentVisitor.visitStringArgument(ctx.stringArgument());
- if (GValue.valueInstanceOf(literalOrVar, String.class)) {
- return this.traversalSource.addE((GValue<String>) literalOrVar);
+ final List<GremlinParser.StringArgumentContext> stringArgs = ctx.stringArgument();
+ if (stringArgs != null && !stringArgs.isEmpty()) {
+ if (stringArgs.size() == 1) {
+ final Object literalOrVar = antlr.argumentVisitor.visitStringArgument(stringArgs.get(0));
+ if (GValue.valueInstanceOf(literalOrVar, String.class)) {
+ return this.traversalSource.addE((GValue<String>) literalOrVar);
+ } else {
+ return this.traversalSource.addE((String) literalOrVar);
+ }
} else {
- return this.traversalSource.addE((String) literalOrVar);
+ // Multi-label: addE("a", "b", ...)
+ final Object firstLiteralOrVar = antlr.argumentVisitor.visitStringArgument(stringArgs.get(0));
+ final String firstLabel = firstLiteralOrVar instanceof String ? (String) firstLiteralOrVar : ((GValue<String>) firstLiteralOrVar).get();
+ final Object secondLiteralOrVar = antlr.argumentVisitor.visitStringArgument(stringArgs.get(1));
+ final String secondLabel = secondLiteralOrVar instanceof String ? (String) secondLiteralOrVar : ((GValue<String>) secondLiteralOrVar).get();
+ final String[] moreLabels = new String[stringArgs.size() - 2];
+ for (int i = 2; i < stringArgs.size(); i++) {
+ final Object literalOrVar = antlr.argumentVisitor.visitStringArgument(stringArgs.get(i));
+ moreLabels[i - 2] = literalOrVar instanceof String ? (String) literalOrVar : ((GValue<String>) literalOrVar).get();
+ }
+ return this.traversalSource.addE(firstLabel, secondLabel, moreLabels);
}
} else if (ctx.nestedTraversal() != null) {
return this.traversalSource.addE(anonymousVisitor.visitNestedTraversal(ctx.nestedTraversal()));
} else {
- throw new IllegalArgumentException("addE with empty arguments is not valid.");
+ return this.traversalSource.addE();
}
}
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/dsl/graph/GraphTraversal.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/dsl/graph/GraphTraversal.java
index 72f08763d1..b402e506a8 100644
--- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/dsl/graph/GraphTraversal.java
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/dsl/graph/GraphTraversal.java
@@ -235,6 +235,7 @@ import java.util.Comparator;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@@ -1500,12 +1501,11 @@ public interface GraphTraversal<S, E> extends Traversal<S, E> {
if (null == l) throw new IllegalArgumentException("vertexLabel cannot be null");
}
this.asAdmin().getGremlinLang().addStep(Symbols.addV, label1, label2, moreLabels);
- this.asAdmin().addStep(new AddVertexStepPlaceholder<>(this.asAdmin(), label1));
- // Add the AddLabelStep directly to avoid double-recording in GremlinLang.
- // The addV step above already recorded all labels; calling t.addLabel() would
- // record an additional addLabel() step in GremlinLang, producing incorrect output
- // like g.addV("a","b").addLabel("b") instead of g.addV("a","b").
- return this.asAdmin().addStep(new AddLabelStep<>(this.asAdmin(), label2, moreLabels));
+ final Set<String> allLabels = new LinkedHashSet<>();
+ allLabels.add(label1);
+ allLabels.add(label2);
+ Collections.addAll(allLabels, moreLabels);
+ return this.asAdmin().addStep(new AddVertexStepPlaceholder<>(this.asAdmin(), allLabels));
}
/**
@@ -1665,6 +1665,29 @@ public interface GraphTraversal<S, E> extends Traversal<S, E> {
return this.asAdmin().addStep(step);
}
+ /**
+ * Multi-label edge creation.
+ *
+ * @param label1 the first label
+ * @param label2 the second label
+ * @param moreLabels additional labels
+ * @return the traversal with the {@link AddEdgeStepContract} added
+ * @since 4.0.0
+ */
+ public default GraphTraversal<S, Edge> addE(final String label1, final String label2, final String... moreLabels) {
+ if (null == label1) throw new IllegalArgumentException("edgeLabel cannot be null");
+ if (null == label2) throw new IllegalArgumentException("edgeLabel cannot be null");
+ for (final String l : moreLabels) {
+ if (null == l) throw new IllegalArgumentException("edgeLabel cannot be null");
+ }
+ this.asAdmin().getGremlinLang().addStep(Symbols.addE, label1, label2, moreLabels);
+ final Set<String> allLabels = new LinkedHashSet<>();
+ allLabels.add(label1);
+ allLabels.add(label2);
+ Collections.addAll(allLabels, moreLabels);
+ return this.asAdmin().addStep(new AddEdgeStepPlaceholder<>(this.asAdmin(), allLabels));
+ }
+
/**
* Provide {@code from()}-modulation to respective steps.
*
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/dsl/graph/GraphTraversalSource.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/dsl/graph/GraphTraversalSource.java
index 0c7715f5af..196019a539 100644
--- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/dsl/graph/GraphTraversalSource.java
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/dsl/graph/GraphTraversalSource.java
@@ -31,7 +31,6 @@ import org.apache.tinkerpop.gremlin.process.traversal.step.GValue;
import org.apache.tinkerpop.gremlin.process.traversal.step.branch.UnionStep;
import org.apache.tinkerpop.gremlin.process.traversal.step.map.AddEdgeStartStepPlaceholder;
import org.apache.tinkerpop.gremlin.process.traversal.step.map.AddVertexStartStepPlaceholder;
-import org.apache.tinkerpop.gremlin.process.traversal.step.sideEffect.AddLabelStep;
import org.apache.tinkerpop.gremlin.process.traversal.step.map.CallStep;
import org.apache.tinkerpop.gremlin.process.traversal.step.map.CallStepPlaceholder;
import org.apache.tinkerpop.gremlin.process.traversal.step.map.DeclarativeMatchStep;
@@ -54,9 +53,12 @@ import org.apache.tinkerpop.gremlin.structure.util.StringFactory;
import org.apache.tinkerpop.gremlin.structure.util.empty.EmptyGraph;
import java.util.Arrays;
+import java.util.Collections;
import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Optional;
+import java.util.Set;
import java.util.function.BinaryOperator;
import java.util.function.Supplier;
import java.util.function.UnaryOperator;
@@ -387,12 +389,11 @@ public class GraphTraversalSource implements TraversalSource {
final GraphTraversalSource clone = this.clone();
clone.gremlinLang.addStep(GraphTraversal.Symbols.addV, label1, label2, moreLabels);
final GraphTraversal.Admin<Vertex, Vertex> traversal = new DefaultGraphTraversal<>(clone);
- traversal.addStep(new AddVertexStartStepPlaceholder(traversal, label1));
- // Add the AddLabelStep directly to avoid double-recording in GremlinLang.
- // The addV step above already recorded all labels; calling t.addLabel() would
- // record an additional addLabel() step in GremlinLang, producing incorrect output
- // like g.addV("a","b").addLabel("b") instead of g.addV("a","b").
- return traversal.addStep(new AddLabelStep<>(traversal, label2, moreLabels));
+ final Set<String> allLabels = new LinkedHashSet<>();
+ allLabels.add(label1);
+ allLabels.add(label2);
+ Collections.addAll(allLabels, moreLabels);
+ return traversal.addStep(new AddVertexStartStepPlaceholder(traversal, allLabels));
}
/**
@@ -431,6 +432,43 @@ public class GraphTraversalSource implements TraversalSource {
return traversal.addStep(new AddEdgeStartStepPlaceholder(traversal, label));
}
+ /**
+ * Spawns a {@link GraphTraversal} by adding an edge with multiple labels.
+ *
+ * @param label1 the first label
+ * @param label2 the second label
+ * @param moreLabels additional labels
+ * @return the traversal with the edge added
+ * @since 4.0.0
+ */
+ public GraphTraversal<Edge, Edge> addE(final String label1, final String label2, final String... moreLabels) {
+ if (null == label1) throw new IllegalArgumentException("edgeLabel cannot be null");
+ if (null == label2) throw new IllegalArgumentException("edgeLabel cannot be null");
+ for (final String l : moreLabels) {
+ if (null == l) throw new IllegalArgumentException("edgeLabel cannot be null");
+ }
+ final GraphTraversalSource clone = this.clone();
+ clone.gremlinLang.addStep(GraphTraversal.Symbols.addE, label1, label2, moreLabels);
+ final GraphTraversal.Admin<Edge, Edge> traversal = new DefaultGraphTraversal<>(clone);
+ final Set<String> allLabels = new LinkedHashSet<>();
+ allLabels.add(label1);
+ allLabels.add(label2);
+ Collections.addAll(allLabels, moreLabels);
+ return traversal.addStep(new AddEdgeStartStepPlaceholder(traversal, allLabels));
+ }
+
+ /**
+ * Spawns a {@link GraphTraversal} by adding an edge with the provider's default label.
+ *
+ * @since 4.0.0
+ */
+ public GraphTraversal<Edge, Edge> addE() {
+ final GraphTraversalSource clone = this.clone();
+ clone.gremlinLang.addStep(GraphTraversal.Symbols.addE);
+ final GraphTraversal.Admin<Edge, Edge> traversal = new DefaultGraphTraversal<>(clone);
+ return traversal.addStep(new AddEdgeStartStepPlaceholder(traversal, (String) null));
+ }
+
/**
* Spawns a {@link GraphTraversal} by doing a merge (i.e. upsert) style operation for an {@link Vertex} using a
* {@code Map} as an argument. The {@code Map} represents search criteria and will match each of the supplied
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/dsl/graph/__.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/dsl/graph/__.java
index 421a1f33ad..506bc4e91f 100644
--- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/dsl/graph/__.java
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/dsl/graph/__.java
@@ -756,6 +756,13 @@ public class __ {
return __.<A>start().addE(edgeLabel);
}
+ /**
+ * @see GraphTraversal#addE(String, String, String...)
+ */
+ public static <A> GraphTraversal<A, Edge> addE(final String label1, final String label2, final String... moreLabels) {
+ return __.<A>start().addE(label1, label2, moreLabels);
+ }
+
/**
* @see GraphTraversal#addE(GValue)
*/
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/AbstractAddEdgeStepPlaceholder.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/AbstractAddEdgeStepPlaceholder.java
index fb1ce7e8c9..95d377c317 100644
--- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/AbstractAddEdgeStepPlaceholder.java
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/AbstractAddEdgeStepPlaceholder.java
@@ -29,6 +29,7 @@ import org.apache.tinkerpop.gremlin.structure.util.reference.ReferenceVertex;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
+import java.util.Set;
public abstract class AbstractAddEdgeStepPlaceholder<S> extends AbstractAddElementStepPlaceholder<S, Edge, Event.EdgeAddedEvent> implements AddEdgeStepContract<S> {
protected Traversal.Admin<?, ?> from;
@@ -42,6 +43,10 @@ public abstract class AbstractAddEdgeStepPlaceholder<S> extends AbstractAddEleme
super(traversal, label);
}
+ public AbstractAddEdgeStepPlaceholder(Traversal.Admin traversal, Set<String> labels) {
+ super(traversal, labels);
+ }
+
public AbstractAddEdgeStepPlaceholder(Traversal.Admin traversal, Traversal.Admin<S, String> labelTraversal) {
super(traversal, labelTraversal);
}
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/AbstractAddElementStepPlaceholder.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/AbstractAddElementStepPlaceholder.java
index 830fef2c80..a2015b4613 100644
--- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/AbstractAddElementStepPlaceholder.java
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/AbstractAddElementStepPlaceholder.java
@@ -61,7 +61,7 @@ public abstract class AbstractAddElementStepPlaceholder<S, E extends Element, X
protected AbstractAddElementStepPlaceholder(final Traversal.Admin traversal, final GValue<String> label) {
super(traversal);
this.label = label == null ? this.getDefaultLabel() : label;
- if (label.isVariable()) {
+ if (label != null && label.isVariable()) {
traversal.getGValueManager().register(label);
}
}
@@ -75,6 +75,11 @@ public abstract class AbstractAddElementStepPlaceholder<S, E extends Element, X
addTraversal(labelTraversal);
}
+ protected AbstractAddElementStepPlaceholder(final Traversal.Admin traversal, final Set<String> labels) {
+ super(traversal);
+ this.label = (labels == null || labels.isEmpty()) ? this.getDefaultLabel() : labels;
+ }
+
protected abstract String getDefaultLabel();
@Override
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/AbstractAddVertexStepPlaceholder.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/AbstractAddVertexStepPlaceholder.java
index 66aa3df116..3e0f0c1c0f 100644
--- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/AbstractAddVertexStepPlaceholder.java
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/AbstractAddVertexStepPlaceholder.java
@@ -25,6 +25,7 @@ import org.apache.tinkerpop.gremlin.process.traversal.step.util.event.Event;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import java.util.Objects;
+import java.util.Set;
public abstract class AbstractAddVertexStepPlaceholder<S> extends AbstractAddElementStepPlaceholder<S, Vertex, Event.VertexAddedEvent>
implements AddVertexStepContract<S>, GValueHolder<S, Vertex> {
@@ -46,6 +47,11 @@ public abstract class AbstractAddVertexStepPlaceholder<S> extends AbstractAddEle
userProvidedLabel = vertexLabelTraversal != null;
}
+ protected AbstractAddVertexStepPlaceholder(final Traversal.Admin traversal, final Set<String> labels) {
+ super(traversal, labels);
+ userProvidedLabel = labels != null && !labels.isEmpty();
+ }
+
@Override
protected String getDefaultLabel() {
return Vertex.DEFAULT_LABEL;
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/AddEdgeStartStep.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/AddEdgeStartStep.java
index 628587a509..99ccd7ce9e 100644
--- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/AddEdgeStartStep.java
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/AddEdgeStartStep.java
@@ -19,7 +19,10 @@
package org.apache.tinkerpop.gremlin.process.traversal.step.map;
+import java.util.Arrays;
import java.util.Collections;
+import java.util.Iterator;
+import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -67,6 +70,15 @@ public class AddEdgeStartStep extends AbstractStep<Edge, Edge> implements AddEdg
this.internalParameters.set(this, T.label, edgeLabelTraversal);
}
+ public AddEdgeStartStep(final Traversal.Admin traversal, final Set<String> labels) {
+ super(traversal);
+ if (labels == null || labels.isEmpty()) {
+ this.internalParameters.set(this, T.label, Edge.DEFAULT_LABEL);
+ } else {
+ this.internalParameters.set(this, T.label, labels);
+ }
+ }
+
@Override
public <S, E> List<Traversal.Admin<S, E>> getLocalChildren() {
return this.internalParameters.getTraversals();
@@ -121,7 +133,21 @@ public class AddEdgeStartStep extends AbstractStep<Edge, Edge> implements AddEdg
// a dead traverser to trigger the traversal
final Traverser.Admin traverser = generator.generate(1, (Step) this, 1);
- final String edgeLabel = (String) this.internalParameters.get(traverser, T.label, () -> Edge.DEFAULT_LABEL).get(0);
+ final Object labelParam = this.internalParameters.get(traverser, T.label, () -> Edge.DEFAULT_LABEL).get(0);
+ final String edgeLabel;
+ final Set<String> additionalLabels;
+ if (labelParam instanceof Set) {
+ final Set<String> labelSet = (Set<String>) labelParam;
+ final Iterator<String> iter = labelSet.iterator();
+ edgeLabel = iter.next();
+ additionalLabels = new LinkedHashSet<>();
+ while (iter.hasNext()) {
+ additionalLabels.add(iter.next());
+ }
+ } else {
+ edgeLabel = (String) labelParam;
+ additionalLabels = Collections.emptySet();
+ }
// FROM/TO must be set and must be vertices
Object theTo = this.internalParameters.get(traverser, TO, () -> null).get(0);
@@ -165,6 +191,10 @@ public class AddEdgeStartStep extends AbstractStep<Edge, Edge> implements AddEdg
}
final Edge edge = fromVertex.addEdge(edgeLabel, toVertex, this.internalParameters.getKeyValues(traverser, TO, FROM, T.label));
+ if (!additionalLabels.isEmpty()) {
+ final String[] extra = additionalLabels.toArray(new String[0]);
+ edge.addLabel(extra[0], Arrays.copyOfRange(extra, 1, extra.length));
+ }
EventUtil.registerEdgeCreation(callbackRegistry, getTraversal(), edge);
return generator.generate(edge, this, 1L);
} else
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/AddEdgeStartStepPlaceholder.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/AddEdgeStartStepPlaceholder.java
index 6042823e17..bbf4d429f3 100644
--- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/AddEdgeStartStepPlaceholder.java
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/AddEdgeStartStepPlaceholder.java
@@ -24,6 +24,8 @@ import org.apache.tinkerpop.gremlin.process.traversal.lambda.GValueConstantTrave
import org.apache.tinkerpop.gremlin.process.traversal.step.GValue;
import org.apache.tinkerpop.gremlin.structure.Edge;
+import java.util.Set;
+
public class AddEdgeStartStepPlaceholder extends AbstractAddEdgeStepPlaceholder<Edge> {
public AddEdgeStartStepPlaceholder(final Traversal.Admin traversal, final String edgeLabel) {
@@ -40,10 +42,16 @@ public class AddEdgeStartStepPlaceholder extends AbstractAddEdgeStepPlaceholder<
(Traversal.Admin<Edge, String>) edgeLabelTraversal);
}
+ public AddEdgeStartStepPlaceholder(final Traversal.Admin traversal, final Set<String> labels) {
+ super(traversal, labels);
+ }
+
@Override
public AddEdgeStartStep asConcreteStep() {
AddEdgeStartStep step;
- if (label instanceof Traversal) {
+ if (label instanceof Set) {
+ step = new AddEdgeStartStep(traversal, (Set<String>) label);
+ } else if (label instanceof Traversal) {
step = new AddEdgeStartStep(traversal, ((Traversal<?, String>) label).asAdmin());
} else if (label instanceof GValue) {
step = new AddEdgeStartStep(traversal, ((GValue<String>) label).get());
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/AddEdgeStep.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/AddEdgeStep.java
index 753d9ae993..7073a7e80f 100644
--- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/AddEdgeStep.java
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/AddEdgeStep.java
@@ -18,7 +18,10 @@
*/
package org.apache.tinkerpop.gremlin.process.traversal.step.map;
+import java.util.Arrays;
import java.util.Collections;
+import java.util.Iterator;
+import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -62,6 +65,15 @@ public class AddEdgeStep<S> extends ScalarMapStep<S, Edge> implements AddEdgeSte
this.internalParameters.set(this, T.label, edgeLabelTraversal);
}
+ public AddEdgeStep(final Traversal.Admin traversal, final Set<String> labels) {
+ super(traversal);
+ if (labels == null || labels.isEmpty()) {
+ this.internalParameters.set(this, T.label, Edge.DEFAULT_LABEL);
+ } else {
+ this.internalParameters.set(this, T.label, labels);
+ }
+ }
+
@Override
public <S, E> List<Traversal.Admin<S, E>> getLocalChildren() {
return this.internalParameters.getTraversals();
@@ -109,7 +121,21 @@ public class AddEdgeStep<S> extends ScalarMapStep<S, Edge> implements AddEdgeSte
@Override
protected Edge map(final Traverser.Admin<S> traverser) {
- final String edgeLabel = this.internalParameters.get(traverser, T.label, () -> Edge.DEFAULT_LABEL).get(0);
+ final Object labelParam = this.internalParameters.get(traverser, T.label, () -> Edge.DEFAULT_LABEL).get(0);
+ final String edgeLabel;
+ final Set<String> additionalLabels;
+ if (labelParam instanceof Set) {
+ final Set<String> labelSet = (Set<String>) labelParam;
+ final Iterator<String> iter = labelSet.iterator();
+ edgeLabel = iter.next();
+ additionalLabels = new LinkedHashSet<>();
+ while (iter.hasNext()) {
+ additionalLabels.add(iter.next());
+ }
+ } else {
+ edgeLabel = (String) labelParam;
+ additionalLabels = Collections.emptySet();
+ }
Vertex toVertex = getAdjacentVertex(this.internalParameters, TO, traverser, edgeLabel);
Vertex fromVertex = getAdjacentVertex(this.internalParameters, FROM, traverser, edgeLabel);
@@ -135,6 +161,10 @@ public class AddEdgeStep<S> extends ScalarMapStep<S, Edge> implements AddEdgeSte
}
final Edge edge = fromVertex.addEdge(edgeLabel, toVertex, this.internalParameters.getKeyValues(traverser, TO, FROM, T.label));
+ if (!additionalLabels.isEmpty()) {
+ final String[] extra = additionalLabels.toArray(new String[0]);
+ edge.addLabel(extra[0], Arrays.copyOfRange(extra, 1, extra.length));
+ }
EventUtil.registerEdgeCreation(callbackRegistry, getTraversal(), edge);
return edge;
}
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/AddEdgeStepPlaceholder.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/AddEdgeStepPlaceholder.java
index a6a5a4466a..a992a1314a 100644
--- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/AddEdgeStepPlaceholder.java
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/AddEdgeStepPlaceholder.java
@@ -24,6 +24,8 @@ import org.apache.tinkerpop.gremlin.process.traversal.lambda.GValueConstantTrave
import org.apache.tinkerpop.gremlin.process.traversal.step.GValue;
import org.apache.tinkerpop.gremlin.structure.Edge;
+import java.util.Set;
+
public class AddEdgeStepPlaceholder<S> extends AbstractAddEdgeStepPlaceholder<S> {
public AddEdgeStepPlaceholder(final Traversal.Admin traversal, final String edgeLabel) {
@@ -39,10 +41,16 @@ public class AddEdgeStepPlaceholder<S> extends AbstractAddEdgeStepPlaceholder<S>
new ConstantTraversal<>(Edge.DEFAULT_LABEL) : edgeLabelTraversal);
}
+ public AddEdgeStepPlaceholder(final Traversal.Admin traversal, final Set<String> labels) {
+ super(traversal, labels);
+ }
+
@Override
public AddEdgeStep<S> asConcreteStep() {
AddEdgeStep<S> step;
- if (label instanceof Traversal) {
+ if (label instanceof Set) {
+ step = new AddEdgeStep<>(traversal, (Set<String>) label);
+ } else if (label instanceof Traversal) {
step = new AddEdgeStep<>(traversal, ((Traversal<S, String>) label).asAdmin());
} else if (label instanceof GValue) {
step = new AddEdgeStep<>(traversal, ((GValue<String>) label).get());
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/AddVertexStartStep.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/AddVertexStartStep.java
index 7718cc2883..5f109ae426 100644
--- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/AddVertexStartStep.java
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/AddVertexStartStep.java
@@ -63,6 +63,17 @@ public class AddVertexStartStep extends AbstractStep<Vertex, Vertex> implements
userProvidedLabel = vertexLabelTraversal != null;
}
+ public AddVertexStartStep(final Traversal.Admin traversal, final Set<String> labels) {
+ super(traversal);
+ if (labels == null || labels.isEmpty()) {
+ this.internalParameters.set(this, T.label, Vertex.DEFAULT_LABEL);
+ userProvidedLabel = false;
+ } else {
+ this.internalParameters.set(this, T.label, labels);
+ userProvidedLabel = true;
+ }
+ }
+
@Override
public boolean hasUserProvidedLabel() {
return userProvidedLabel;
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/AddVertexStartStepPlaceholder.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/AddVertexStartStepPlaceholder.java
index e84f4a7f1c..a1b5fa2449 100644
--- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/AddVertexStartStepPlaceholder.java
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/AddVertexStartStepPlaceholder.java
@@ -24,6 +24,8 @@ import org.apache.tinkerpop.gremlin.process.traversal.step.GValue;
import org.apache.tinkerpop.gremlin.process.traversal.step.GValueHolder;
import org.apache.tinkerpop.gremlin.structure.Vertex;
+import java.util.Set;
+
public class AddVertexStartStepPlaceholder extends AbstractAddVertexStepPlaceholder<Vertex>
implements AddVertexStepContract<Vertex>, GValueHolder<Vertex, Vertex> {
@@ -40,10 +42,16 @@ public class AddVertexStartStepPlaceholder extends AbstractAddVertexStepPlacehol
new ConstantTraversal<>(Vertex.DEFAULT_LABEL) : (Traversal.Admin<Vertex,String>) vertexLabelTraversal);
}
+ public AddVertexStartStepPlaceholder(final Traversal.Admin traversal, final Set<String> labels) {
+ super(traversal, labels);
+ }
+
@Override
public AddVertexStartStep asConcreteStep() {
AddVertexStartStep step;
- if (label instanceof Traversal) {
+ if (label instanceof Set) {
+ step = new AddVertexStartStep(traversal, (Set<String>) label);
+ } else if (label instanceof Traversal) {
step = new AddVertexStartStep(traversal, ((Traversal<?, String>) label).asAdmin());
} else if (label instanceof GValue) {
step = new AddVertexStartStep(traversal, ((GValue<String>) label).get());
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/AddVertexStep.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/AddVertexStep.java
index b015920e17..4c2b505b53 100644
--- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/AddVertexStep.java
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/AddVertexStep.java
@@ -59,6 +59,17 @@ public class AddVertexStep<S> extends ScalarMapStep<S, Vertex> implements AddVer
userProvidedLabel = vertexLabelTraversal != null;
}
+ public AddVertexStep(final Traversal.Admin traversal, final Set<String> labels) {
+ super(traversal);
+ if (labels == null || labels.isEmpty()) {
+ this.internalParameters.set(this, T.label, Vertex.DEFAULT_LABEL);
+ userProvidedLabel = false;
+ } else {
+ this.internalParameters.set(this, T.label, labels);
+ userProvidedLabel = true;
+ }
+ }
+
@Override
public boolean hasUserProvidedLabel() {
return userProvidedLabel;
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/AddVertexStepPlaceholder.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/AddVertexStepPlaceholder.java
index 505bc47c1f..b749760051 100644
--- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/AddVertexStepPlaceholder.java
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/AddVertexStepPlaceholder.java
@@ -22,6 +22,8 @@ import org.apache.tinkerpop.gremlin.process.traversal.Traversal;
import org.apache.tinkerpop.gremlin.process.traversal.lambda.GValueConstantTraversal;
import org.apache.tinkerpop.gremlin.process.traversal.step.GValue;
+import java.util.Set;
+
public class AddVertexStepPlaceholder<S> extends AbstractAddVertexStepPlaceholder<S> {
public AddVertexStepPlaceholder(Traversal.Admin traversal, String label) {
@@ -36,10 +38,16 @@ public class AddVertexStepPlaceholder<S> extends AbstractAddVertexStepPlaceholde
super(traversal, vertexLabelTraversal);
}
+ public AddVertexStepPlaceholder(Traversal.Admin traversal, Set<String> labels) {
+ super(traversal, labels);
+ }
+
@Override
public AddVertexStep<S> asConcreteStep() {
AddVertexStep<S> step;
- if (label instanceof Traversal) {
+ if (label instanceof Set) {
+ step = new AddVertexStep<>(traversal, (Set<String>) label);
+ } else if (label instanceof Traversal) {
step = new AddVertexStep<>(traversal, ((Traversal<S, String>) label).asAdmin());
} else if (label instanceof GValue) {
step = new AddVertexStep<>(traversal, ((GValue<String>) label).get());
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/ElementMapStep.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/ElementMapStep.java
index 370b0cd059..b05e620849 100644
--- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/ElementMapStep.java
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/ElementMapStep.java
@@ -25,7 +25,6 @@ import org.apache.tinkerpop.gremlin.process.traversal.step.GraphComputing;
import org.apache.tinkerpop.gremlin.process.traversal.step.TraversalParent;
import org.apache.tinkerpop.gremlin.process.traversal.step.util.Parameters;
import org.apache.tinkerpop.gremlin.process.traversal.step.util.WithOptions;
-import org.apache.tinkerpop.gremlin.process.traversal.strategy.decoration.OptionsStrategy;
import org.apache.tinkerpop.gremlin.process.traversal.traverser.TraverserRequirement;
import org.apache.tinkerpop.gremlin.structure.Direction;
import org.apache.tinkerpop.gremlin.structure.Edge;
@@ -131,10 +130,7 @@ public class ElementMapStep<K,E> extends ScalarMapStep<Element, Map<K, E>> imple
* or source-level {@code g.with("multilabel")}.
*/
private boolean isMultilabelEnabled() {
- if (this.multilabel) return true;
- return getTraversal().getStrategies().getStrategy(OptionsStrategy.class)
- .map(os -> os.getOptions().containsKey("multilabel") || os.getOptions().containsKey(WithOptions.multilabel))
- .orElse(false);
+ return WithOptions.isMultilabelEnabled(this.multilabel, getTraversal());
}
public String[] getPropertyKeys() {
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/MergeEdgeStep.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/MergeEdgeStep.java
index 3535143192..261ab78eb8 100644
--- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/MergeEdgeStep.java
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/MergeEdgeStep.java
@@ -20,6 +20,7 @@ package org.apache.tinkerpop.gremlin.process.traversal.step.map;
import java.util.ArrayList;
import java.util.Arrays;
+import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
@@ -166,17 +167,21 @@ public class MergeEdgeStep<S> extends MergeElementStep<S, Edge, Map<Object, Obje
final Graph graph = getGraph();
final Object edgeId = search.get(T.id);
- final String edgeLabel = (String) search.get(T.label);
+ final Object labelValue = search.get(T.label);
final Object fromId = search.get(Direction.OUT);
final Object toId = search.get(Direction.IN);
+ // Extract a single label string for use in outE(label)/inE(label) calls.
+ // For multi-label (collection), we use hasLabel() chaining instead.
+ final String singleLabel = labelValue instanceof String ? (String) labelValue : null;
+ final boolean hasLabelConstraint = labelValue != null;
+
GraphTraversal t;
if (edgeId != null) {
// g.E(eid).hasLabel(label).where(outV().hasId(fromId)).where(inV().hasId(toId));
t = graph.traversal().E(edgeId);
- if (edgeLabel != null)
- t = t.hasLabel(edgeLabel);
+ t = applyLabelConstraint(t, labelValue);
if (fromId != null)
t = t.where(outV().hasId(fromId));
if (toId != null)
@@ -186,10 +191,14 @@ public class MergeEdgeStep<S> extends MergeElementStep<S, Edge, Map<Object, Obje
// g.V(fromId).outE(label).where(inV().hasId(toId));
t = graph.traversal().V(fromId);
- if (edgeLabel != null)
- t = t.outE(edgeLabel);
- else
+ if (singleLabel != null)
+ t = t.outE(singleLabel);
+ else {
t = t.outE();
+ // apply multi-label constraint after outE() if it's a collection
+ if (hasLabelConstraint && singleLabel == null)
+ t = applyLabelConstraint(t, labelValue);
+ }
if (toId != null)
t = t.where(inV().hasId(toId));
@@ -197,17 +206,20 @@ public class MergeEdgeStep<S> extends MergeElementStep<S, Edge, Map<Object, Obje
// g.V(toId).inE(edgeLabel);
t = graph.traversal().V(toId);
- if (edgeLabel != null)
- t = t.inE(edgeLabel);
- else
+ if (singleLabel != null)
+ t = t.inE(singleLabel);
+ else {
t = t.inE();
+ // apply multi-label constraint after inE() if it's a collection
+ if (hasLabelConstraint && singleLabel == null)
+ t = applyLabelConstraint(t, labelValue);
+ }
} else {
// g.E().hasLabel(label)
t = graph.traversal().E();
- if (edgeLabel != null)
- t = t.hasLabel(edgeLabel);
+ t = applyLabelConstraint(t, labelValue);
}
@@ -222,6 +234,26 @@ public class MergeEdgeStep<S> extends MergeElementStep<S, Edge, Map<Object, Obje
return CloseableIterator.of(t);
}
+ /**
+ * Apply label constraint(s) to the traversal. Supports both single String labels and
+ * Collection labels with AND semantics (edge must have ALL specified labels).
+ */
+ protected GraphTraversal applyLabelConstraint(GraphTraversal t, final Object labelValue) {
+ if (labelValue == null) {
+ return t;
+ }
+ if (labelValue instanceof String) {
+ return t.hasLabel((String) labelValue);
+ } else if (labelValue instanceof java.util.Collection) {
+ // Multi-label: AND semantics - must have ALL specified labels
+ for (final Object label : (java.util.Collection<?>) labelValue) {
+ t = t.hasLabel((String) label);
+ }
+ return t;
+ }
+ return t;
+ }
+
protected Map<?,?> resolveVertices(final Map map, final Traverser.Admin<S> traverser) {
resolveVertex(Merge.outV, Direction.OUT, map, traverser, outVTraversal);
resolveVertex(Merge.inV, Direction.IN, map, traverser, inVTraversal);
@@ -279,14 +311,34 @@ public class MergeEdgeStep<S> extends MergeElementStep<S, Edge, Map<Object, Obje
traverser.set((S) e);
// assume good input from GraphTraversal - folks might drop in a T here even though it is immutable
- final Map<String, ?> onMatchMap = materializeMap(traverser, onMatchTraversal);
+ final Map onMatchMap = materializeMap(traverser, onMatchTraversal);
validateMapInput(onMatchMap, true);
onMatchMap.forEach((key, value) -> {
+ // Handle T.label replacement for multi-label support
+ if (T.label.equals(key) || T.label.getAccessor().equals(key)) {
+ // Drop all existing labels and replace with new ones
+ e.dropLabels();
+ if (value instanceof String) {
+ e.addLabel((String) value);
+ } else if (value instanceof java.util.Collection) {
+ final java.util.Collection<?> labels = (java.util.Collection<?>) value;
+ if (!labels.isEmpty()) {
+ final String[] labelArray = labels.stream()
+ .map(l -> (String) l)
+ .toArray(String[]::new);
+ e.addLabel(labelArray[0],
+ Arrays.copyOfRange(labelArray, 1, labelArray.length));
+ }
+ // Empty collection = use default label behavior (already handled by dropLabels())
+ }
+ return;
+ }
+
// trigger callbacks for eventing - in this case, it's a EdgePropertyChangedEvent. if there's no
// registry/callbacks then just set the property
- EventUtil.registerEdgePropertyChange(callbackRegistry, getTraversal(), e, key, value);
- e.property(key, value);
+ EventUtil.registerEdgePropertyChange(callbackRegistry, getTraversal(), e, (String) key, value);
+ e.property((String) key, value);
});
});
@@ -317,7 +369,30 @@ public class MergeEdgeStep<S> extends MergeElementStep<S, Edge, Map<Object, Obje
final Vertex fromV = resolveVertex(onCreateMap.get(Direction.OUT));
final Vertex toV = resolveVertex(onCreateMap.get(Direction.IN));
- final String label = (String) onCreateMap.getOrDefault(T.label, Edge.DEFAULT_LABEL);
+ final Object labelValue = onCreateMap.getOrDefault(T.label, Edge.DEFAULT_LABEL);
+ final String primaryLabel;
+ final java.util.Collection<String> additionalLabels;
+
+ if (labelValue instanceof String) {
+ primaryLabel = (String) labelValue;
+ additionalLabels = Collections.emptyList();
+ } else if (labelValue instanceof java.util.Collection) {
+ final java.util.Collection<?> labelCollection = (java.util.Collection<?>) labelValue;
+ if (labelCollection.isEmpty()) {
+ primaryLabel = Edge.DEFAULT_LABEL;
+ additionalLabels = Collections.emptyList();
+ } else {
+ final Iterator<?> iter = labelCollection.iterator();
+ primaryLabel = (String) iter.next();
+ additionalLabels = new ArrayList<>();
+ while (iter.hasNext()) {
+ additionalLabels.add((String) iter.next());
+ }
+ }
+ } else {
+ primaryLabel = Edge.DEFAULT_LABEL;
+ additionalLabels = Collections.emptyList();
+ }
final List<Object> properties = new ArrayList<>();
@@ -329,7 +404,13 @@ public class MergeEdgeStep<S> extends MergeElementStep<S, Edge, Map<Object, Obje
properties.add(e.getValue());
}
- final Edge edge = fromV.addEdge(label, toV, properties.toArray());
+ final Edge edge = fromV.addEdge(primaryLabel, toV, properties.toArray());
+
+ // add any additional labels from a multi-label collection
+ if (!additionalLabels.isEmpty()) {
+ final String[] extraLabels = additionalLabels.toArray(new String[0]);
+ edge.addLabel(extraLabels[0], Arrays.copyOfRange(extraLabels, 1, extraLabels.length));
+ }
// trigger callbacks for eventing - in this case, it's a VertexAddedEvent
EventUtil.registerEdgeCreationWithGenericEventRegistry(callbackRegistry, getTraversal(), edge);
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/PropertyMapStep.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/PropertyMapStep.java
index 25bc143bc3..665ea10e4b 100644
--- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/PropertyMapStep.java
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/PropertyMapStep.java
@@ -25,7 +25,6 @@ import org.apache.tinkerpop.gremlin.process.traversal.step.Configuring;
import org.apache.tinkerpop.gremlin.process.traversal.step.TraversalParent;
import org.apache.tinkerpop.gremlin.process.traversal.step.util.Parameters;
import org.apache.tinkerpop.gremlin.process.traversal.step.util.WithOptions;
-import org.apache.tinkerpop.gremlin.process.traversal.strategy.decoration.OptionsStrategy;
import org.apache.tinkerpop.gremlin.process.traversal.traverser.TraverserRequirement;
import org.apache.tinkerpop.gremlin.process.traversal.util.TraversalProduct;
import org.apache.tinkerpop.gremlin.process.traversal.util.TraversalUtil;
@@ -220,10 +219,7 @@ public class PropertyMapStep<K,E> extends ScalarMapStep<Element, Map<K, E>>
* or source-level {@code g.with("multilabel")}.
*/
private boolean isMultilabelEnabled() {
- if (this.multilabel) return true;
- return getTraversal().getStrategies().getStrategy(OptionsStrategy.class)
- .map(os -> os.getOptions().containsKey("multilabel") || os.getOptions().containsKey(WithOptions.multilabel))
- .orElse(false);
+ return WithOptions.isMultilabelEnabled(this.multilabel, getTraversal());
}
protected Object getElementId(Element element){
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/sideEffect/AddLabelStep.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/sideEffect/AddLabelStep.java
index c239623601..1cb2d01108 100644
--- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/sideEffect/AddLabelStep.java
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/sideEffect/AddLabelStep.java
@@ -26,7 +26,6 @@ import org.apache.tinkerpop.gremlin.process.traversal.step.util.event.CallbackRe
import org.apache.tinkerpop.gremlin.process.traversal.step.util.event.Event;
import org.apache.tinkerpop.gremlin.process.traversal.step.util.event.EventUtil;
import org.apache.tinkerpop.gremlin.process.traversal.step.util.event.ListCallbackRegistry;
-import org.apache.tinkerpop.gremlin.process.traversal.strategy.decoration.EventStrategy;
import org.apache.tinkerpop.gremlin.process.traversal.traverser.TraverserRequirement;
import org.apache.tinkerpop.gremlin.process.traversal.util.TraversalUtil;
import org.apache.tinkerpop.gremlin.structure.Element;
@@ -36,9 +35,9 @@ import org.apache.tinkerpop.gremlin.structure.util.StringFactory;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
+import java.util.LinkedHashSet;
import java.util.List;
import java.util.Objects;
-import java.util.Optional;
import java.util.Set;
/**
@@ -48,11 +47,11 @@ import java.util.Set;
* @since 4.0.0
*/
public class AddLabelStep<S extends Element> extends SideEffectStep<S>
- implements Mutating<Event.ElementPropertyChangedEvent>, TraversalParent {
+ implements Mutating<Event.ElementLabelChangedEvent>, TraversalParent {
private final String[] labels;
private Traversal.Admin<S, String> labelTraversal;
- private CallbackRegistry<Event.ElementPropertyChangedEvent> callbackRegistry;
+ private CallbackRegistry<Event.ElementLabelChangedEvent> callbackRegistry;
public AddLabelStep(final Traversal.Admin traversal, final String label, final String... moreLabels) {
super(traversal);
@@ -76,6 +75,7 @@ public class AddLabelStep<S extends Element> extends SideEffectStep<S>
@Override
protected void sideEffect(final Traverser.Admin<S> traverser) {
final Element element = traverser.get();
+ final Set<String> oldLabels = new LinkedHashSet<>(element.labels());
if (this.labelTraversal != null) {
final List<String> collectedLabels = new ArrayList<>();
@@ -93,16 +93,14 @@ public class AddLabelStep<S extends Element> extends SideEffectStep<S>
Arrays.copyOfRange(this.labels, 1, this.labels.length));
}
- // trigger event callbacks
- final Optional<EventStrategy> optEventStrategy = getTraversal().getStrategies().getStrategy(EventStrategy.class);
- if (EventUtil.hasAnyCallbacks(callbackRegistry) && optEventStrategy.isPresent()) {
- final EventStrategy es = optEventStrategy.get();
- EventUtil.registerPropertyChange(callbackRegistry, es, element, null, null, new Object[0]);
+ // trigger event callbacks only if labels actually changed
+ if (!oldLabels.equals(element.labels())) {
+ EventUtil.registerLabelChange(callbackRegistry, getTraversal(), element, oldLabels, element.labels());
}
}
@Override
- public CallbackRegistry<Event.ElementPropertyChangedEvent> getMutatingCallbackRegistry() {
+ public CallbackRegistry<Event.ElementLabelChangedEvent> getMutatingCallbackRegistry() {
if (null == callbackRegistry) callbackRegistry = new ListCallbackRegistry<>();
return callbackRegistry;
}
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/sideEffect/DropLabelsStep.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/sideEffect/DropLabelsStep.java
index 14e5d0634f..9812b0b786 100644
--- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/sideEffect/DropLabelsStep.java
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/sideEffect/DropLabelsStep.java
@@ -26,7 +26,6 @@ import org.apache.tinkerpop.gremlin.process.traversal.step.util.event.CallbackRe
import org.apache.tinkerpop.gremlin.process.traversal.step.util.event.Event;
import org.apache.tinkerpop.gremlin.process.traversal.step.util.event.EventUtil;
import org.apache.tinkerpop.gremlin.process.traversal.step.util.event.ListCallbackRegistry;
-import org.apache.tinkerpop.gremlin.process.traversal.strategy.decoration.EventStrategy;
import org.apache.tinkerpop.gremlin.process.traversal.traverser.TraverserRequirement;
import org.apache.tinkerpop.gremlin.process.traversal.util.TraversalUtil;
import org.apache.tinkerpop.gremlin.structure.Element;
@@ -35,8 +34,8 @@ import org.apache.tinkerpop.gremlin.structure.util.StringFactory;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
+import java.util.LinkedHashSet;
import java.util.List;
-import java.util.Optional;
import java.util.Set;
/**
@@ -46,12 +45,12 @@ import java.util.Set;
* @since 4.0.0
*/
public class DropLabelsStep<S extends Element> extends SideEffectStep<S>
- implements Mutating<Event.ElementPropertyChangedEvent>, TraversalParent {
+ implements Mutating<Event.ElementLabelChangedEvent>, TraversalParent {
private final boolean dropAll;
private final String[] labels;
private Traversal.Admin<S, String> labelTraversal;
- private CallbackRegistry<Event.ElementPropertyChangedEvent> callbackRegistry;
+ private CallbackRegistry<Event.ElementLabelChangedEvent> callbackRegistry;
/**
* Constructor for dropLabels() - removes all labels.
@@ -89,6 +88,7 @@ public class DropLabelsStep<S extends Element> extends SideEffectStep<S>
@Override
protected void sideEffect(final Traverser.Admin<S> traverser) {
final Element element = traverser.get();
+ final Set<String> oldLabels = new LinkedHashSet<>(element.labels());
if (this.labelTraversal != null) {
final String label = TraversalUtil.apply(traverser, this.labelTraversal);
@@ -102,16 +102,14 @@ public class DropLabelsStep<S extends Element> extends SideEffectStep<S>
Arrays.copyOfRange(this.labels, 1, this.labels.length));
}
- // trigger event callbacks
- final Optional<EventStrategy> optEventStrategy = getTraversal().getStrategies().getStrategy(EventStrategy.class);
- if (EventUtil.hasAnyCallbacks(callbackRegistry) && optEventStrategy.isPresent()) {
- final EventStrategy es = optEventStrategy.get();
- EventUtil.registerPropertyChange(callbackRegistry, es, element, null, null, new Object[0]);
+ // trigger event callbacks only if labels actually changed
+ if (!oldLabels.equals(element.labels())) {
+ EventUtil.registerLabelChange(callbackRegistry, getTraversal(), element, oldLabels, element.labels());
}
}
@Override
- public CallbackRegistry<Event.ElementPropertyChangedEvent> getMutatingCallbackRegistry() {
+ public CallbackRegistry<Event.ElementLabelChangedEvent> getMutatingCallbackRegistry() {
if (null == callbackRegistry) callbackRegistry = new ListCallbackRegistry<>();
return callbackRegistry;
}
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/util/WithOptions.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/util/WithOptions.java
index d9101feb97..dd139ca7ba 100644
--- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/util/WithOptions.java
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/util/WithOptions.java
@@ -18,8 +18,10 @@
*/
package org.apache.tinkerpop.gremlin.process.traversal.step.util;
+import org.apache.tinkerpop.gremlin.process.traversal.Traversal;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
import org.apache.tinkerpop.gremlin.process.traversal.step.map.IndexStep;
+import org.apache.tinkerpop.gremlin.process.traversal.strategy.decoration.OptionsStrategy;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Element;
import org.apache.tinkerpop.gremlin.structure.Graph;
@@ -112,4 +114,20 @@ public class WithOptions {
* @since 4.0.0
*/
public static final String multilabel = Graph.Hidden.hide("tinkerpop.multilabel");
+
+ /**
+ * The user-facing key for multilabel configuration used with {@code g.with("multilabel")}.
+ */
+ public static final String MULTILABEL_KEY = "multilabel";
+
+ /**
+ * Checks whether multi-label output is enabled for the given traversal, either at the step level
+ * (via step-level configuration) or at the source level (via {@code g.with("multilabel")}).
+ */
+ public static boolean isMultilabelEnabled(final boolean stepLevelEnabled, final Traversal.Admin<?, ?> traversal) {
+ if (stepLevelEnabled) return true;
+ return traversal.getStrategies().getStrategy(OptionsStrategy.class)
+ .map(os -> os.getOptions().containsKey(MULTILABEL_KEY) || os.getOptions().containsKey(multilabel))
+ .orElse(false);
+ }
}
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/util/event/Event.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/util/event/Event.java
index 4a9d9c06e6..f02e6bc63f 100644
--- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/util/event/Event.java
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/util/event/Event.java
@@ -27,6 +27,7 @@ import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.structure.VertexProperty;
import java.util.Iterator;
+import java.util.Set;
/**
* A representation of some action that occurs on a {@link Graph} for a {@link Traversal}.
@@ -213,6 +214,31 @@ public interface Event {
}
}
+ /**
+ * An event that represents a label change on an element (vertex or edge).
+ * Fired when labels are added or removed via addLabel()/dropLabel()/dropLabels() steps.
+ */
+ class ElementLabelChangedEvent implements Event {
+ private final Element element;
+ private final Set<String> oldLabels;
+ private final Set<String> newLabels;
+
+ public ElementLabelChangedEvent(final Element element, final Set<String> oldLabels, final Set<String> newLabels) {
+ this.element = element;
+ this.oldLabels = oldLabels;
+ this.newLabels = newLabels;
+ }
+
+ public Element getElement() { return element; }
+ public Set<String> getOldLabels() { return oldLabels; }
+ public Set<String> getNewLabels() { return newLabels; }
+
+ @Override
+ public void fireEvent(final Iterator<MutationListener> eventListeners) {
+ // Label change events are dispatched directly via CallbackRegistry, not MutationListener.
+ }
+ }
+
/**
* A base class for {@link Property} mutation events.
*/
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/util/event/EventUtil.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/util/event/EventUtil.java
index 2fce97e150..85d8072f89 100644
--- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/util/event/EventUtil.java
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/util/event/EventUtil.java
@@ -27,6 +27,8 @@ import org.apache.tinkerpop.gremlin.structure.Property;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.structure.VertexProperty;
+import java.util.Set;
+
/**
* Logic for registering events with the {@link EventStrategy} and the callback registry. Extracting this logic allows
* providers to reuse these utilities more readily.
@@ -202,6 +204,24 @@ public final class EventUtil {
}
}
+ /**
+ * Register a label change event with the callback registry.
+ */
+ @SuppressWarnings("unchecked")
+ public static void registerLabelChange(final CallbackRegistry<Event.ElementLabelChangedEvent> callbackRegistry,
+ final Traversal.Admin<?, ?> traversal, final Element element,
+ final Set<String> oldLabels, final Set<String> newLabels) {
+ if (hasAnyCallbacks(callbackRegistry)) {
+ final EventStrategy eventStrategy = ((Traversal.Admin<Object, Object>) traversal)
+ .getStrategies().getStrategy(EventStrategy.class).orElse(null);
+ final Element detachedElement = eventStrategy != null ? eventStrategy.detach(element) : element;
+ final Event.ElementLabelChangedEvent event = new Event.ElementLabelChangedEvent(detachedElement, oldLabels, newLabels);
+ for (EventCallback<Event.ElementLabelChangedEvent> c : callbackRegistry.getCallbacks()) {
+ c.accept(event);
+ }
+ }
+ }
+
/**
* Register a vertex property addition event with the callback registry.
*/
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/io/binary/types/EdgeSerializer.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/io/binary/types/EdgeSerializer.java
index 6d614d5126..fe48d6f6ae 100644
--- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/io/binary/types/EdgeSerializer.java
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/io/binary/types/EdgeSerializer.java
@@ -30,8 +30,11 @@ import org.apache.tinkerpop.gremlin.structure.util.detached.DetachedVertex;
import org.apache.tinkerpop.gremlin.structure.util.reference.ReferenceEdge;
import java.io.IOException;
+import java.util.ArrayList;
import java.util.Collections;
+import java.util.LinkedHashSet;
import java.util.List;
+import java.util.Set;
/**
* @author Stephen Mallette (http://stephen.genoprime.com)
@@ -44,25 +47,43 @@ public class EdgeSerializer extends SimpleTypeSerializer<Edge> {
@Override
protected Edge readValue(final Buffer buffer, final GraphBinaryReader context) throws IOException {
final Object id = context.read(buffer);
- // reading single string value for now according to GraphBinaryV4
- final String label = (String) context.readValue(buffer, List.class, false).get(0);
+ // Read all labels as List<String> for multi-label support
+ final List<String> labelList = context.readValue(buffer, List.class, false);
final Object inVId = context.read(buffer);
- // reading single string value for now according to GraphBinaryV4
- final String inVLabel = (String) context.readValue(buffer, List.class, false).get(0);
+ // Read all inVertex labels as List<String> for multi-label support
+ final List<String> inVLabelList = context.readValue(buffer, List.class, false);
final Object outVId = context.read(buffer);
- // reading single string value for now according to GraphBinaryV4
- final String outVLabel = (String) context.readValue(buffer, List.class, false).get(0);
+ // Read all outVertex labels as List<String> for multi-label support
+ final List<String> outVLabelList = context.readValue(buffer, List.class, false);
// discard the parent vertex
context.read(buffer);
final List<Property> properties = context.read(buffer);
- final DetachedVertex inV = DetachedVertex.build().setId(inVId).setLabel(inVLabel).create();
- final DetachedVertex outV = DetachedVertex.build().setId(outVId).setLabel(outVLabel).create();
+ final DetachedVertex.Builder inVBuilder = DetachedVertex.build().setId(inVId);
+ if (inVLabelList.size() == 1) {
+ inVBuilder.setLabel(inVLabelList.get(0));
+ } else if (!inVLabelList.isEmpty()) {
+ inVBuilder.setLabels(new LinkedHashSet<>(inVLabelList));
+ }
+ final DetachedVertex inV = inVBuilder.create();
+
+ final DetachedVertex.Builder outVBuilder = DetachedVertex.build().setId(outVId);
+ if (outVLabelList.size() == 1) {
+ outVBuilder.setLabel(outVLabelList.get(0));
+ } else if (!outVLabelList.isEmpty()) {
+ outVBuilder.setLabels(new LinkedHashSet<>(outVLabelList));
+ }
+ final DetachedVertex outV = outVBuilder.create();
- final DetachedEdge.Builder builder = DetachedEdge.build().setId(id).setLabel(label).setInV(inV).setOutV(outV);
+ final DetachedEdge.Builder builder = DetachedEdge.build().setId(id).setInV(inV).setOutV(outV);
+ if (labelList.size() == 1) {
+ builder.setLabel(labelList.get(0));
+ } else if (!labelList.isEmpty()) {
+ builder.setLabels(new LinkedHashSet<>(labelList));
+ }
if (properties != null) {
for (final Property p : properties) {
@@ -77,16 +98,28 @@ public class EdgeSerializer extends SimpleTypeSerializer<Edge> {
protected void writeValue(final Edge value, final Buffer buffer, final GraphBinaryWriter context) throws IOException {
context.write(value.id(), buffer);
- // wrapping label into list here for now according to GraphBinaryV4, but we aren't allowing null label yet
- if (value.label() == null) {
- throw new IOException("Unexpected null value when nullable is false");
+ // Write all edge labels as List<String> for multi-label support
+ final Set<String> edgeLabels = value.labels();
+ if (edgeLabels == null || edgeLabels.isEmpty()) {
+ throw new IOException("Unexpected null or empty labels when nullable is false");
}
- context.writeValue(Collections.singletonList(value.label()), buffer, false);
+ context.writeValue(new ArrayList<>(edgeLabels), buffer, false);
context.write(value.inVertex().id(), buffer);
- context.writeValue(Collections.singletonList(value.inVertex().label()), buffer, false);
+ // Write all inVertex labels as List<String> for multi-label support
+ final Set<String> inVLabels = value.inVertex().labels();
+ if (inVLabels == null || inVLabels.isEmpty()) {
+ throw new IOException("Unexpected null or empty labels when nullable is false");
+ }
+ context.writeValue(new ArrayList<>(inVLabels), buffer, false);
+
context.write(value.outVertex().id(), buffer);
- context.writeValue(Collections.singletonList(value.outVertex().label()), buffer, false);
+ // Write all outVertex labels as List<String> for multi-label support
+ final Set<String> outVLabels = value.outVertex().labels();
+ if (outVLabels == null || outVLabels.isEmpty()) {
+ throw new IOException("Unexpected null or empty labels when nullable is false");
+ }
+ context.writeValue(new ArrayList<>(outVLabels), buffer, false);
// we don't serialize the parent Vertex for edges.
context.write(null, buffer);
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/io/graphson/GraphSONSerializersV4.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/io/graphson/GraphSONSerializersV4.java
index 3fd6815077..cad3bb5276 100644
--- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/io/graphson/GraphSONSerializersV4.java
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/io/graphson/GraphSONSerializersV4.java
@@ -146,7 +146,7 @@ class GraphSONSerializersV4 {
jsonGenerator.writeStartObject();
jsonGenerator.writeObjectField(GraphSONTokens.ID, edge.id());
- writeLabel(jsonGenerator, GraphSONTokens.LABEL, edge.label());
+ writeLabels(jsonGenerator, GraphSONTokens.LABEL, edge.labels());
writeTypeForGraphObjectIfUntyped(jsonGenerator, typeInfo, GraphSONTokens.EDGE);
writeVertex(GraphSONTokens.IN, edge.inVertex(), jsonGenerator);
writeVertex(GraphSONTokens.OUT, edge.outVertex(), jsonGenerator);
@@ -160,7 +160,7 @@ class GraphSONSerializersV4 {
jsonGenerator.writeFieldName(vertexDirection);
jsonGenerator.writeStartObject();
jsonGenerator.writeObjectField(GraphSONTokens.ID, v.id());
- writeLabel(jsonGenerator, GraphSONTokens.LABEL, v.label());
+ writeLabels(jsonGenerator, GraphSONTokens.LABEL, v.labels());
jsonGenerator.writeEndObject();
}
@@ -438,8 +438,14 @@ class GraphSONSerializersV4 {
e.setId(deserializationContext.readValue(jsonParser, Object.class));
} else if (jsonParser.getCurrentName().equals(GraphSONTokens.LABEL)) {
jsonParser.nextToken();
+ final java.util.Set<String> labels = new java.util.LinkedHashSet<>();
while (jsonParser.nextToken() != JsonToken.END_ARRAY) {
- e.setLabel(jsonParser.getText());
+ labels.add(jsonParser.getText());
+ }
+ if (labels.size() == 1) {
+ e.setLabel(labels.iterator().next());
+ } else if (!labels.isEmpty()) {
+ e.setLabels(labels);
}
} else if (jsonParser.getCurrentName().equals(GraphSONTokens.OUT)) {
jsonParser.nextToken();
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/util/detached/DetachedEdge.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/util/detached/DetachedEdge.java
index 2c91afb615..77f53876d4 100644
--- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/util/detached/DetachedEdge.java
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/util/detached/DetachedEdge.java
@@ -30,8 +30,10 @@ import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
+import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
+import java.util.Set;
/**
* Represents an {@link Edge} that is disconnected from a {@link Graph}. "Disconnection" can mean detachment from
@@ -51,6 +53,7 @@ public class DetachedEdge extends DetachedElement<Edge> implements Edge {
private DetachedVertex outVertex;
private DetachedVertex inVertex;
+ private Set<String> edgeLabels;
private DetachedEdge() {}
@@ -59,6 +62,12 @@ public class DetachedEdge extends DetachedElement<Edge> implements Edge {
this.outVertex = DetachedFactory.detach(edge.outVertex(), false);
this.inVertex = DetachedFactory.detach(edge.inVertex(), false);
+ // Capture all labels from the source edge for multi-label support.
+ final Set<String> srcLabels = edge.labels();
+ if (srcLabels.size() > 1) {
+ this.edgeLabels = new LinkedHashSet<>(srcLabels);
+ }
+
// only serialize properties if requested, the graph supports it and there are meta properties present.
// this prevents unnecessary object creation of a new HashMap of a new HashMap which will just be empty.
// it will use Collections.emptyMap() by default
@@ -113,6 +122,23 @@ public class DetachedEdge extends DetachedElement<Edge> implements Edge {
return StringFactory.edgeString(this);
}
+ @Override
+ public Set<String> labels() {
+ if (this.edgeLabels != null) {
+ return Collections.unmodifiableSet(this.edgeLabels);
+ }
+ // Fall back to single label from parent
+ return this.label != null ? Collections.singleton(this.label) : Collections.emptySet();
+ }
+
+ @Override
+ public String label() {
+ if (this.edgeLabels != null && !this.edgeLabels.isEmpty()) {
+ return this.edgeLabels.iterator().next();
+ }
+ return this.label != null ? this.label : Edge.DEFAULT_LABEL;
+ }
+
@Override
public Vertex inVertex() {
return this.inVertex;
@@ -180,6 +206,14 @@ public class DetachedEdge extends DetachedElement<Edge> implements Edge {
return this;
}
+ public Builder setLabels(final Set<String> labels) {
+ e.edgeLabels = labels != null ? new LinkedHashSet<>(labels) : null;
+ if (labels != null && !labels.isEmpty()) {
+ e.label = labels.iterator().next();
+ }
+ return this;
+ }
+
public Builder setOutV(final DetachedVertex v) {
e.outVertex = v;
return this;
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/util/reference/ReferenceEdge.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/util/reference/ReferenceEdge.java
index 6f716022ef..8f797b96b3 100644
--- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/util/reference/ReferenceEdge.java
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/util/reference/ReferenceEdge.java
@@ -28,6 +28,8 @@ import org.apache.tinkerpop.gremlin.util.iterator.IteratorUtils;
import java.util.Collections;
import java.util.Iterator;
+import java.util.LinkedHashSet;
+import java.util.Set;
/**
* @author Marko A. Rodriguez (http://markorodriguez.com)
@@ -36,6 +38,7 @@ public class ReferenceEdge extends ReferenceElement<Edge> implements Edge {
private ReferenceVertex inVertex;
private ReferenceVertex outVertex;
+ private Set<String> edgeLabels;
private ReferenceEdge() {
@@ -45,6 +48,11 @@ public class ReferenceEdge extends ReferenceElement<Edge> implements Edge {
super(edge);
this.inVertex = new ReferenceVertex(edge.inVertex());
this.outVertex = new ReferenceVertex(edge.outVertex());
+ // Capture all labels from the source edge for multi-label support.
+ final Set<String> srcLabels = edge.labels();
+ if (srcLabels.size() > 1) {
+ this.edgeLabels = new LinkedHashSet<>(srcLabels);
+ }
}
public ReferenceEdge(final Object id, final String label, final ReferenceVertex inVertex, final ReferenceVertex outVertex) {
@@ -53,6 +61,29 @@ public class ReferenceEdge extends ReferenceElement<Edge> implements Edge {
this.outVertex = outVertex;
}
+ public ReferenceEdge(final Object id, final Set<String> labels, final ReferenceVertex inVertex, final ReferenceVertex outVertex) {
+ super(id, labels != null && !labels.isEmpty() ? labels.iterator().next() : Edge.DEFAULT_LABEL);
+ this.edgeLabels = labels != null ? new LinkedHashSet<>(labels) : null;
+ this.inVertex = inVertex;
+ this.outVertex = outVertex;
+ }
+
+ @Override
+ public Set<String> labels() {
+ if (this.edgeLabels != null) {
+ return Collections.unmodifiableSet(this.edgeLabels);
+ }
+ return this.label != null ? Collections.singleton(this.label) : Collections.emptySet();
+ }
+
+ @Override
+ public String label() {
+ if (this.edgeLabels != null && !this.edgeLabels.isEmpty()) {
+ return this.edgeLabels.iterator().next();
+ }
+ return this.label != null ? this.label : Edge.DEFAULT_LABEL;
+ }
+
@Override
public <V> Property<V> property(final String key, final V value) {
throw Element.Exceptions.propertyAdditionNotSupported();
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/util/star/StarGraph.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/util/star/StarGraph.java
index 8daaf64aef..1981a3257b 100644
--- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/util/star/StarGraph.java
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/util/star/StarGraph.java
@@ -43,6 +43,7 @@ import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
+import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
@@ -206,6 +207,12 @@ public final class StarGraph implements Graph, Serializable {
final StarGraph starGraph = new StarGraph();
final StarVertex starVertex = (StarVertex) starGraph.addVertex(T.id, vertex.id(), T.label, vertex.label());
+ // Copy multi-labels from source vertex
+ final Set<String> srcLabels = vertex.labels();
+ if (srcLabels.size() > 1) {
+ starVertex.setLabels(srcLabels);
+ }
+
final boolean supportsMetaProperties = vertex.graph().features().vertex().supportsMetaProperties();
vertex.properties().forEachRemaining(vp -> {
@@ -216,11 +223,19 @@ public final class StarGraph implements Graph, Serializable {
vertex.edges(Direction.IN).forEachRemaining(edge -> {
final Edge starEdge = starVertex.addInEdge(edge.label(), starGraph.addVertex(T.id, edge.outVertex().id()), T.id, edge.id());
edge.properties().forEachRemaining(p -> starEdge.property(p.key(), p.value()));
+ final Set<String> edgeSrcLabels = edge.labels();
+ if (edgeSrcLabels.size() > 1) {
+ ((StarGraph.StarEdge) starEdge).setLabels(edgeSrcLabels);
+ }
});
vertex.edges(Direction.OUT).forEachRemaining(edge -> {
final Edge starEdge = starVertex.addOutEdge(edge.label(), starGraph.addVertex(T.id, edge.inVertex().id()), T.id, edge.id());
edge.properties().forEachRemaining(p -> starEdge.property(p.key(), p.value()));
+ final Set<String> edgeSrcLabels = edge.labels();
+ if (edgeSrcLabels.size() > 1) {
+ ((StarGraph.StarEdge) starEdge).setLabels(edgeSrcLabels);
+ }
});
return starGraph;
}
@@ -308,7 +323,7 @@ public final class StarGraph implements Graph, Serializable {
public abstract class StarElement<E extends Element> implements Element, Attachable<E> {
protected final Object id;
- protected final String label;
+ protected String label;
protected StarElement(final Object id, final String label) {
this.id = id;
@@ -352,12 +367,35 @@ public final class StarGraph implements Graph, Serializable {
public final class StarVertex extends StarElement<Vertex> implements Vertex {
+ private Set<String> vertexLabels;
protected Map<String, List<Edge>> outEdges = null;
protected Map<String, List<Edge>> inEdges = null;
protected Map<String, List<VertexProperty>> vertexProperties = null;
public StarVertex(final Object id, final String label) {
super(id, label);
+ this.vertexLabels = new LinkedHashSet<>();
+ this.vertexLabels.add(internStrings ? label.intern() : label);
+ }
+
+ @Override
+ public Set<String> labels() {
+ return Collections.unmodifiableSet(this.vertexLabels);
+ }
+
+ @Override
+ public String label() {
+ return this.vertexLabels.isEmpty() ? this.label : this.vertexLabels.iterator().next();
+ }
+
+ /**
+ * Sets the vertex labels from a source set. Used when copying labels from a multi-label vertex.
+ */
+ public void setLabels(final Set<String> labels) {
+ if (labels != null && !labels.isEmpty()) {
+ this.vertexLabels = new LinkedHashSet<>(labels);
+ this.label = this.vertexLabels.iterator().next();
+ }
}
private void dropEdgeProperty(Object id) {
@@ -774,11 +812,34 @@ public final class StarGraph implements Graph, Serializable {
public abstract class StarEdge extends StarElement<Edge> implements Edge {
+ private Set<String> edgeLabels;
protected final Object otherId;
private StarEdge(final Object id, final String label, final Object otherId) {
super(id, label);
this.otherId = otherId;
+ this.edgeLabels = new LinkedHashSet<>();
+ this.edgeLabels.add(internStrings ? label.intern() : label);
+ }
+
+ @Override
+ public Set<String> labels() {
+ return Collections.unmodifiableSet(this.edgeLabels);
+ }
+
+ @Override
+ public String label() {
+ return this.edgeLabels.isEmpty() ? this.label : this.edgeLabels.iterator().next();
+ }
+
+ /**
+ * Sets the edge labels from a source set. Used when copying labels from a multi-label edge.
+ */
+ public void setLabels(final Set<String> labels) {
+ if (labels != null && !labels.isEmpty()) {
+ this.edgeLabels = new LinkedHashSet<>(labels);
+ this.label = this.edgeLabels.iterator().next();
+ }
}
@Override
diff --git a/gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Gherkin/GherkinTestRunner.cs b/gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Gherkin/GherkinTestRunner.cs
index 6aee902762..04969b5fae 100644
--- a/gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Gherkin/GherkinTestRunner.cs
+++ b/gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Gherkin/GherkinTestRunner.cs
@@ -125,6 +125,12 @@ namespace Gremlin.Net.IntegrationTest.Gherkin
continue;
}
+ if (scenario.Tags.Any(t => t.Name == "@MultiLabel"))
+ {
+ failedSteps.Add(scenario.Steps.First(), new IgnoreException(IgnoreReason.MultiLabelStepsNotSupported));
+ continue;
+ }
+
StepBlock? currentStep = null;
StepDefinition? stepDefinition = null;
foreach (var step in scenario.Steps)
diff --git a/gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Gherkin/IgnoreException.cs b/gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Gherkin/IgnoreException.cs
index 7001391004..bf3918f253 100644
--- a/gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Gherkin/IgnoreException.cs
+++ b/gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Gherkin/IgnoreException.cs
@@ -70,6 +70,11 @@ namespace Gremlin.Net.IntegrationTest.Gherkin
/// <summary>
/// write() is not supported yet for testing
/// </summary>
- WriteStepTestingNotSupported
+ WriteStepTestingNotSupported,
+
+ /// <summary>
+ /// Multi-label steps (labels(), addLabel(), dropLabel(), dropLabels()) are not yet available in the .NET GLV
+ /// </summary>
+ MultiLabelStepsNotSupported
}
}
\ No newline at end of file
diff --git a/gremlin-go/driver/cucumber/cucumberSteps_test.go b/gremlin-go/driver/cucumber/cucumberSteps_test.go
index 149bc9bc07..fd69c063d0 100644
--- a/gremlin-go/driver/cucumber/cucumberSteps_test.go
+++ b/gremlin-go/driver/cucumber/cucumberSteps_test.go
@@ -1130,6 +1130,7 @@ func TestCucumberFeatures(t *testing.T) {
ScenarioInitializer: InitializeScenario,
Options: &godog.Options{
Tags: "~@GraphComputerOnly && ~@AllowNullPropertyValues && ~@StepTree && ~@StepWrite && ~@DataChar",
+ Tags: "~@GraphComputerOnly && ~@AllowNullPropertyValues && ~@StepTree && ~@StepWrite && ~@DataChar && ~@MultiLabel",
Format: "pretty",
Paths: []string{getEnvOrDefaultString("CUCUMBER_FEATURE_FOLDER", "../../../gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/test/features")},
TestingT: t, // Testing instance that will run subtests.
diff --git a/gremlin-js/gremlin-javascript/test/cucumber/world.js b/gremlin-js/gremlin-javascript/test/cucumber/world.js
index 563abb8ce8..8dcd7d18ba 100644
--- a/gremlin-js/gremlin-javascript/test/cucumber/world.js
+++ b/gremlin-js/gremlin-javascript/test/cucumber/world.js
@@ -118,6 +118,10 @@ Before({tags: "@DataDuration"}, function() {
return 'skipped'
})
+Before({tags: "@MultiLabel"}, function() {
+ return 'skipped'
+})
+
function getVertices(connection) {
const g = anon.traversal().withRemote(connection);
return g.V().group().by('name').by(__.tail()).next().then(it => {
diff --git a/gremlin-language/src/main/antlr4/Gremlin.g4 b/gremlin-language/src/main/antlr4/Gremlin.g4
index f10489dd1b..3392483b08 100644
--- a/gremlin-language/src/main/antlr4/Gremlin.g4
+++ b/gremlin-language/src/main/antlr4/Gremlin.g4
@@ -112,7 +112,9 @@ traversalSourceSpawnMethod
;
traversalSourceSpawnMethod_addE
- : K_ADDE LPAREN stringArgument RPAREN
+ : K_ADDE LPAREN RPAREN
+ | K_ADDE LPAREN stringArgument RPAREN
+ | K_ADDE LPAREN stringArgument COMMA stringArgument (COMMA stringArgument)* RPAREN
| K_ADDE LPAREN nestedTraversal RPAREN
;
@@ -331,7 +333,9 @@ traversalMethod_E
;
traversalMethod_addE
- : K_ADDE LPAREN stringArgument RPAREN #traversalMethod_addE_String
+ : K_ADDE LPAREN RPAREN #traversalMethod_addE_Empty
+ | K_ADDE LPAREN stringArgument RPAREN #traversalMethod_addE_String
+ | K_ADDE LPAREN stringArgument (COMMA stringArgument)+ RPAREN #traversalMethod_addE_StringVarargs
| K_ADDE LPAREN nestedTraversal RPAREN #traversalMethod_addE_Traversal
;
diff --git a/gremlin-python/src/main/python/tests/feature/feature_steps.py b/gremlin-python/src/main/python/tests/feature/feature_steps.py
index f40c3fa91e..56feab3a29 100644
--- a/gremlin-python/src/main/python/tests/feature/feature_steps.py
+++ b/gremlin-python/src/main/python/tests/feature/feature_steps.py
@@ -90,6 +90,10 @@ def choose_graph(step, graph_name):
if not step.context.ignore:
step.context.ignore = "WithReservedKeysVerificationStrategy" in tagset
+ # Multi-label steps not yet available in Python GLV
+ if not step.context.ignore:
+ step.context.ignore = "MultiLabel" in tagset
+
if (step.context.ignore):
return
diff --git a/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/language/translator/translations.json b/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/language/translator/translations.json
index f152691348..aaf373e313 100644
--- a/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/language/translator/translations.json
+++ b/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/language/translator/translations.json
@@ -19290,6 +19290,76 @@
}
]
},
+ {
+ "scenario": "g_addVXa_bX_labels",
+ "traversals": [
+ {
+ "original": "g.addV(\"a\", \"b\").labels().fold()",
+ "language": "g.addV(\"a\", \"b\").labels().fold()",
+ "canonical": "g.addV(\"a\", \"b\").labels().fold()",
+ "anonymized": "g.addV(string0, string1).labels().fold()",
+ "dotnet": "g.AddV((string) \"a\", (string) \"b\").Labels().Fold()",
+ "go": "g.AddV(\"a\", \"b\").Labels().Fold()",
+ "groovy": "g.addV(\"a\", \"b\").labels().fold()",
+ "java": "g.addV(\"a\", \"b\").labels().fold()",
+ "javascript": "g.addV(\"a\", \"b\").labels().fold()",
+ "python": "g.add_v('a', 'b').labels().fold()"
+ },
+ {
+ "original": "g.V().hasLabel(\"a\").hasLabel(\"b\")",
+ "language": "g.V().hasLabel(\"a\").hasLabel(\"b\")",
+ "canonical": "g.V().hasLabel(\"a\").hasLabel(\"b\")",
+ "anonymized": "g.V().hasLabel(string0).hasLabel(string1)",
+ "dotnet": "g.V().HasLabel(\"a\").HasLabel(\"b\")",
+ "go": "g.V().HasLabel(\"a\").HasLabel(\"b\")",
+ "groovy": "g.V().hasLabel(\"a\").hasLabel(\"b\")",
+ "java": "g.V().hasLabel(\"a\").hasLabel(\"b\")",
+ "javascript": "g.V().hasLabel(\"a\").hasLabel(\"b\")",
+ "python": "g.V().has_label('a').has_label('b')"
+ },
+ {
+ "original": "g.addV(\"a\", \"b\")",
+ "language": "g.addV(\"a\", \"b\")",
+ "canonical": "g.addV(\"a\", \"b\")",
+ "anonymized": "g.addV(string0, string1)",
+ "dotnet": "g.AddV((string) \"a\", (string) \"b\")",
+ "go": "g.AddV(\"a\", \"b\")",
+ "groovy": "g.addV(\"a\", \"b\")",
+ "java": "g.addV(\"a\", \"b\")",
+ "javascript": "g.addV(\"a\", \"b\")",
+ "python": "g.add_v('a', 'b')"
+ },
+ {
+ "original": "g.V().labels()",
+ "language": "g.V().labels()",
+ "canonical": "g.V().labels()",
+ "anonymized": "g.V().labels()",
+ "dotnet": "g.V().Labels()",
+ "go": "g.V().Labels()",
+ "groovy": "g.V().labels()",
+ "java": "g.V().labels()",
+ "javascript": "g.V().labels()",
+ "python": "g.V().labels()"
+ }
+ ]
+ },
+ {
+ "scenario": "g_addVXa_b_cX_labels_count",
+ "traversals": [
+ {
+ "original": "g.addV(\"a\", \"b\", \"c\").labels().count()",
+ "language": "g.addV(\"a\", \"b\", \"c\").labels().count()",
+ "canonical": "g.addV(\"a\", \"b\", \"c\").labels().count()",
+ "anonymized": "g.addV(string0, string1, string2).labels().count()",
+ "dotnet": "g.AddV((string) \"a\", (string) \"b\", (string) \"c\").Labels().Count()",
+ "go": "g.AddV(\"a\", \"b\", \"c\").Labels().Count()",
+ "groovy": "g.addV(\"a\", \"b\", \"c\").labels().count()",
+ "java": "g.addV(\"a\", \"b\", \"c\").labels().count()",
+ "javascript": "g.addV(\"a\", \"b\", \"c\").labels().count()",
+ "python": "g.add_v('a', 'b', 'c').labels().count()"
+ }
+ ]
+ },
{
"scenario": "g_injectX1X_asBool",
"traversals": [
@@ -24396,6 +24466,127 @@
}
]
},
+ {
+ "scenario": "g_V_hasLabelXpersonX_labels",
+ "traversals": [
+ {
+ "original": "g.V().hasLabel(\"person\").labels()",
+ "language": "g.V().hasLabel(\"person\").labels()",
+ "canonical": "g.V().hasLabel(\"person\").labels()",
+ "anonymized": "g.V().hasLabel(string0).labels()",
+ "dotnet": "g.V().HasLabel(\"person\").Labels()",
+ "go": "g.V().HasLabel(\"person\").Labels()",
+ "groovy": "g.V().hasLabel(\"person\").labels()",
+ "java": "g.V().hasLabel(\"person\").labels()",
+ "javascript": "g.V().hasLabel(\"person\").labels()",
+ "python": "g.V().has_label('person').labels()"
+ }
+ ]
+ },
+ {
+ "scenario": "g_addVXa_bX_labels_fold",
+ "traversals": [
+ {
+ "original": "g.addV(\"a\", \"b\")",
+ "language": "g.addV(\"a\", \"b\")",
+ "canonical": "g.addV(\"a\", \"b\")",
+ "anonymized": "g.addV(string0, string1)",
+ "dotnet": "g.AddV((string) \"a\", (string) \"b\")",
+ "go": "g.AddV(\"a\", \"b\")",
+ "groovy": "g.addV(\"a\", \"b\")",
+ "java": "g.addV(\"a\", \"b\")",
+ "javascript": "g.addV(\"a\", \"b\")",
+ "python": "g.add_v('a', 'b')"
+ },
+ {
+ "original": "g.V().labels().fold()",
+ "language": "g.V().labels().fold()",
+ "canonical": "g.V().labels().fold()",
+ "anonymized": "g.V().labels().fold()",
+ "dotnet": "g.V().Labels().Fold()",
+ "go": "g.V().Labels().Fold()",
+ "groovy": "g.V().labels().fold()",
+ "java": "g.V().labels().fold()",
+ "javascript": "g.V().labels().fold()",
+ "python": "g.V().labels().fold()"
+ }
+ ]
+ },
+ {
+ "scenario": "g_addVXa_bX_labels_count",
+ "traversals": [
+ {
+ "original": "g.addV(\"a\", \"b\")",
+ "language": "g.addV(\"a\", \"b\")",
+ "canonical": "g.addV(\"a\", \"b\")",
+ "anonymized": "g.addV(string0, string1)",
+ "dotnet": "g.AddV((string) \"a\", (string) \"b\")",
+ "go": "g.AddV(\"a\", \"b\")",
+ "groovy": "g.addV(\"a\", \"b\")",
+ "java": "g.addV(\"a\", \"b\")",
+ "javascript": "g.addV(\"a\", \"b\")",
+ "python": "g.add_v('a', 'b')"
+ },
+ {
+ "original": "g.V().labels().count()",
+ "language": "g.V().labels().count()",
+ "canonical": "g.V().labels().count()",
+ "anonymized": "g.V().labels().count()",
+ "dotnet": "g.V().Labels().Count()",
+ "go": "g.V().Labels().Count()",
+ "groovy": "g.V().labels().count()",
+ "java": "g.V().labels().count()",
+ "javascript": "g.V().labels().count()",
+ "python": "g.V().labels().count()"
+ }
+ ]
+ },
+ {
+ "scenario": "g_addV_labels",
+ "traversals": [
+ {
+ "original": "g.addV()",
+ "language": "g.addV()",
+ "canonical": "g.addV()",
+ "anonymized": "g.addV()",
+ "dotnet": "g.AddV()",
+ "go": "g.AddV()",
+ "groovy": "g.addV()",
+ "java": "g.addV()",
+ "javascript": "g.addV()",
+ "python": "g.add_v()"
+ },
+ {
+ "original": "g.V().labels()",
+ "language": "g.V().labels()",
+ "canonical": "g.V().labels()",
+ "anonymized": "g.V().labels()",
+ "dotnet": "g.V().Labels()",
+ "go": "g.V().Labels()",
+ "groovy": "g.V().labels()",
+ "java": "g.V().labels()",
+ "javascript": "g.V().labels()",
+ "python": "g.V().labels()"
+ }
+ ]
+ },
+ {
+ "scenario": "g_E_labels",
+ "traversals": [
+ {
+ "original": "g.E().hasLabel(\"knows\").labels()",
+ "language": "g.E().hasLabel(\"knows\").labels()",
+ "canonical": "g.E().hasLabel(\"knows\").labels()",
+ "anonymized": "g.E().hasLabel(string0).labels()",
+ "dotnet": "g.E().HasLabel(\"knows\").Labels()",
+ "go": "g.E().HasLabel(\"knows\").Labels()",
+ "groovy": "g.E().hasLabel(\"knows\").labels()",
+ "java": "g.E().hasLabel(\"knows\").labels()",
+ "javascript": "g.E().hasLabel(\"knows\").labels()",
+ "python": "g.E().has_label('knows').labels()"
+ }
+ ]
+ },
{
"scenario": "g_injectXfeature_test_nullX_length",
"traversals": [
@@ -32674,6 +32865,454 @@
}
]
},
+ {
+ "scenario": "g_mergeVXlabel_ab_name_markoX_multilabel_create",
+ "traversals": [
+ {
+ "original": "g.mergeV([(T.label): [\"person\",\"employee\"], name: \"marko\"])",
+ "language": "g.mergeV([(T.label):[\"person\", \"employee\"], name:\"marko\"])",
+ "canonical": "g.mergeV([(T.label):[\"person\", \"employee\"], name:\"marko\"])",
+ "anonymized": "g.mergeV(map0)",
+ "dotnet": "g.MergeV((IDictionary<object, object>) new Dictionary<object, object> {{ T.Label, new List<object> { \"person\", \"employee\" } }, { \"name\", \"marko\" }})",
+ "go": "g.MergeV(map[interface{}]interface{}{gremlingo.T.Label: []interface{}{\"person\", \"employee\"}, \"name\": \"marko\" })",
+ "groovy": "g.mergeV([(T.label):[\"person\", \"employee\"], name:\"marko\"])",
+ "java": "g.mergeV(new LinkedHashMap<Object, Object>() {{ put(T.label, new ArrayList<Object>() {{ add(\"person\"); add(\"employee\"); }}); put(\"name\", \"marko\"); }})",
+ "javascript": "g.mergeV(new Map([[T.label, [\"person\", \"employee\"]], [\"name\", \"marko\"]]))",
+ "python": "g.merge_v({ T.label: ['person', 'employee'], 'name': 'marko' })"
+ },
+ {
+ "original": "g.V()",
+ "language": "g.V()",
+ "canonical": "g.V()",
+ "anonymized": "g.V()",
+ "dotnet": "g.V()",
+ "go": "g.V()",
+ "groovy": "g.V()",
+ "java": "g.V()",
+ "javascript": "g.V()",
+ "python": "g.V()"
+ },
+ {
+ "original": "g.V().hasLabel(\"person\").hasLabel(\"employee\")",
+ "language": "g.V().hasLabel(\"person\").hasLabel(\"employee\")",
+ "canonical": "g.V().hasLabel(\"person\").hasLabel(\"employee\")",
+ "anonymized": "g.V().hasLabel(string0).hasLabel(string1)",
+ "dotnet": "g.V().HasLabel(\"person\").HasLabel(\"employee\")",
+ "go": "g.V().HasLabel(\"person\").HasLabel(\"employee\")",
+ "groovy": "g.V().hasLabel(\"person\").hasLabel(\"employee\")",
+ "java": "g.V().hasLabel(\"person\").hasLabel(\"employee\")",
+ "javascript": "g.V().hasLabel(\"person\").hasLabel(\"employee\")",
+ "python": "g.V().has_label('person').has_label('employee')"
+ },
+ {
+ "original": "g.V().has(\"name\",\"marko\")",
+ "language": "g.V().has(\"name\", \"marko\")",
+ "canonical": "g.V().has(\"name\", \"marko\")",
+ "anonymized": "g.V().has(string0, string1)",
+ "dotnet": "g.V().Has(\"name\", \"marko\")",
+ "go": "g.V().Has(\"name\", \"marko\")",
+ "groovy": "g.V().has(\"name\", \"marko\")",
+ "java": "g.V().has(\"name\", \"marko\")",
+ "javascript": "g.V().has(\"name\", \"marko\")",
+ "python": "g.V().has('name', 'marko')"
+ }
+ ]
+ },
+ {
+ "scenario": "g_mergeVXlabel_abc_name_testX_multilabel_create",
+ "traversals": [
+ {
+ "original": "g.mergeV([(T.label): [\"a\",\"b\",\"c\"], name: \"test\"])",
+ "language": "g.mergeV([(T.label):[\"a\", \"b\", \"c\"], name:\"test\"])",
+ "canonical": "g.mergeV([(T.label):[\"a\", \"b\", \"c\"], name:\"test\"])",
+ "anonymized": "g.mergeV(map0)",
+ "dotnet": "g.MergeV((IDictionary<object, object>) new Dictionary<object, object> {{ T.Label, new List<object> { \"a\", \"b\", \"c\" } }, { \"name\", \"test\" }})",
+ "go": "g.MergeV(map[interface{}]interface{}{gremlingo.T.Label: []interface{}{\"a\", \"b\", \"c\"}, \"name\": \"test\" })",
+ "groovy": "g.mergeV([(T.label):[\"a\", \"b\", \"c\"], name:\"test\"])",
+ "java": "g.mergeV(new LinkedHashMap<Object, Object>() {{ put(T.label, new ArrayList<Object>() {{ add(\"a\"); add(\"b\"); add(\"c\"); }}); put(\"name\", \"test\"); }})",
+ "javascript": "g.mergeV(new Map([[T.label, [\"a\", \"b\", \"c\"]], [\"name\", \"test\"]]))",
+ "python": "g.merge_v({ T.label: ['a', 'b', 'c'], 'name': 'test' })"
+ },
+ {
+ "original": "g.V()",
+ "language": "g.V()",
+ "canonical": "g.V()",
+ "anonymized": "g.V()",
+ "dotnet": "g.V()",
+ "go": "g.V()",
+ "groovy": "g.V()",
+ "java": "g.V()",
+ "javascript": "g.V()",
+ "python": "g.V()"
+ },
+ {
+ "original": "g.V().hasLabel(\"a\").hasLabel(\"b\").hasLabel(\"c\")",
+ "language": "g.V().hasLabel(\"a\").hasLabel(\"b\").hasLabel(\"c\")",
+ "canonical": "g.V().hasLabel(\"a\").hasLabel(\"b\").hasLabel(\"c\")",
+ "anonymized": "g.V().hasLabel(string0).hasLabel(string1).hasLabel(string2)",
+ "dotnet": "g.V().HasLabel(\"a\").HasLabel(\"b\").HasLabel(\"c\")",
+ "go": "g.V().HasLabel(\"a\").HasLabel(\"b\").HasLabel(\"c\")",
+ "groovy": "g.V().hasLabel(\"a\").hasLabel(\"b\").hasLabel(\"c\")",
+ "java": "g.V().hasLabel(\"a\").hasLabel(\"b\").hasLabel(\"c\")",
+ "javascript": "g.V().hasLabel(\"a\").hasLabel(\"b\").hasLabel(\"c\")",
+ "python": "g.V().has_label('a').has_label('b').has_label('c')"
+ }
+ ]
+ },
+ {
+ "scenario": "g_mergeVXlabel_person_name_markoX_single_label",
+ "traversals": [
+ {
+ "original": "g.mergeV([(T.label): \"person\", name: \"marko\"])",
+ "language": "g.mergeV([(T.label):\"person\", name:\"marko\"])",
+ "canonical": "g.mergeV([(T.label):\"person\", name:\"marko\"])",
+ "anonymized": "g.mergeV(map0)",
+ "dotnet": "g.MergeV((IDictionary<object, object>) new Dictionary<object, object> {{ T.Label, \"person\" }, { \"name\", \"marko\" }})",
+ "go": "g.MergeV(map[interface{}]interface{}{gremlingo.T.Label: \"person\", \"name\": \"marko\" })",
+ "groovy": "g.mergeV([(T.label):\"person\", name:\"marko\"])",
+ "java": "g.mergeV(new LinkedHashMap<Object, Object>() {{ put(T.label, \"person\"); put(\"name\", \"marko\"); }})",
+ "javascript": "g.mergeV(new Map([[T.label, \"person\"], [\"name\", \"marko\"]]))",
+ "python": "g.merge_v({ T.label: 'person', 'name': 'marko' })"
+ },
+ {
+ "original": "g.V()",
+ "language": "g.V()",
+ "canonical": "g.V()",
+ "anonymized": "g.V()",
+ "dotnet": "g.V()",
+ "go": "g.V()",
+ "groovy": "g.V()",
+ "java": "g.V()",
+ "javascript": "g.V()",
+ "python": "g.V()"
+ },
+ {
+ "original": "g.V().hasLabel(\"person\")",
+ "language": "g.V().hasLabel(\"person\")",
+ "canonical": "g.V().hasLabel(\"person\")",
+ "anonymized": "g.V().hasLabel(string0)",
+ "dotnet": "g.V().HasLabel(\"person\")",
+ "go": "g.V().HasLabel(\"person\")",
+ "groovy": "g.V().hasLabel(\"person\")",
+ "java": "g.V().hasLabel(\"person\")",
+ "javascript": "g.V().hasLabel(\"person\")",
+ "python": "g.V().has_label('person')"
+ },
+ {
+ "original": "g.V().has(\"name\",\"marko\")",
+ "language": "g.V().has(\"name\", \"marko\")",
+ "canonical": "g.V().has(\"name\", \"marko\")",
+ "anonymized": "g.V().has(string0, string1)",
+ "dotnet": "g.V().Has(\"name\", \"marko\")",
+ "go": "g.V().Has(\"name\", \"marko\")",
+ "groovy": "g.V().has(\"name\", \"marko\")",
+ "java": "g.V().has(\"name\", \"marko\")",
+ "javascript": "g.V().has(\"name\", \"marko\")",
+ "python": "g.V().has('name', 'marko')"
+ }
+ ]
+ },
+ {
+ "scenario": "g_mergeVXlabel_ab_name_markoX_multilabel_match",
+ "traversals": [
+ {
+ "original": "g.addV(\"person\").addLabel(\"employee\").property(\"name\", \"marko\")",
+ "language": "g.addV(\"person\").addLabel(\"employee\").property(\"name\", \"marko\")",
+ "canonical": "g.addV(\"person\").addLabel(\"employee\").property(\"name\", \"marko\")",
+ "anonymized": "g.addV(string0).addLabel(string1).property(string2, string3)",
+ "dotnet": "g.AddV((string) \"person\").AddLabel(\"employee\").Property(\"name\", \"marko\")",
+ "go": "g.AddV(\"person\").AddLabel(\"employee\").Property(\"name\", \"marko\")",
+ "groovy": "g.addV(\"person\").addLabel(\"employee\").property(\"name\", \"marko\")",
+ "java": "g.addV(\"person\").addLabel(\"employee\").property(\"name\", \"marko\")",
+ "javascript": "g.addV(\"person\").addLabel(\"employee\").property(\"name\", \"marko\")",
+ "python": "g.add_v('person').add_label('employee').property('name', 'marko')"
+ },
+ {
+ "original": "g.mergeV([(T.label): [\"person\",\"employee\"], name: \"marko\"])",
+ "language": "g.mergeV([(T.label):[\"person\", \"employee\"], name:\"marko\"])",
+ "canonical": "g.mergeV([(T.label):[\"person\", \"employee\"], name:\"marko\"])",
+ "anonymized": "g.mergeV(map0)",
+ "dotnet": "g.MergeV((IDictionary<object, object>) new Dictionary<object, object> {{ T.Label, new List<object> { \"person\", \"employee\" } }, { \"name\", \"marko\" }})",
+ "go": "g.MergeV(map[interface{}]interface{}{gremlingo.T.Label: []interface{}{\"person\", \"employee\"}, \"name\": \"marko\" })",
+ "groovy": "g.mergeV([(T.label):[\"person\", \"employee\"], name:\"marko\"])",
+ "java": "g.mergeV(new LinkedHashMap<Object, Object>() {{ put(T.label, new ArrayList<Object>() {{ add(\"person\"); add(\"employee\"); }}); put(\"name\", \"marko\"); }})",
+ "javascript": "g.mergeV(new Map([[T.label, [\"person\", \"employee\"]], [\"name\", \"marko\"]]))",
+ "python": "g.merge_v({ T.label: ['person', 'employee'], 'name': 'marko' })"
+ },
+ {
+ "original": "g.V()",
+ "language": "g.V()",
+ "canonical": "g.V()",
+ "anonymized": "g.V()",
+ "dotnet": "g.V()",
+ "go": "g.V()",
+ "groovy": "g.V()",
+ "java": "g.V()",
+ "javascript": "g.V()",
+ "python": "g.V()"
+ },
+ {
+ "original": "g.V().hasLabel(\"person\").hasLabel(\"employee\")",
+ "language": "g.V().hasLabel(\"person\").hasLabel(\"employee\")",
+ "canonical": "g.V().hasLabel(\"person\").hasLabel(\"employee\")",
+ "anonymized": "g.V().hasLabel(string0).hasLabel(string1)",
+ "dotnet": "g.V().HasLabel(\"person\").HasLabel(\"employee\")",
+ "go": "g.V().HasLabel(\"person\").HasLabel(\"employee\")",
+ "groovy": "g.V().hasLabel(\"person\").hasLabel(\"employee\")",
+ "java": "g.V().hasLabel(\"person\").hasLabel(\"employee\")",
+ "javascript": "g.V().hasLabel(\"person\").hasLabel(\"employee\")",
+ "python": "g.V().has_label('person').has_label('employee')"
+ }
+ ]
+ },
+ {
+ "scenario": "g_mergeVXlabel_ab_name_markoX_multilabel_nomatch",
+ "traversals": [
+ {
+ "original": "g.addV(\"person\").property(\"name\", \"marko\")",
+ "language": "g.addV(\"person\").property(\"name\", \"marko\")",
+ "canonical": "g.addV(\"person\").property(\"name\", \"marko\")",
+ "anonymized": "g.addV(string0).property(string1, string2)",
+ "dotnet": "g.AddV((string) \"person\").Property(\"name\", \"marko\")",
+ "go": "g.AddV(\"person\").Property(\"name\", \"marko\")",
+ "groovy": "g.addV(\"person\").property(\"name\", \"marko\")",
+ "java": "g.addV(\"person\").property(\"name\", \"marko\")",
+ "javascript": "g.addV(\"person\").property(\"name\", \"marko\")",
+ "python": "g.add_v('person').property('name', 'marko')"
+ },
+ {
+ "original": "g.mergeV([(T.label): [\"person\",\"employee\"], name: \"marko\"])",
+ "language": "g.mergeV([(T.label):[\"person\", \"employee\"], name:\"marko\"])",
+ "canonical": "g.mergeV([(T.label):[\"person\", \"employee\"], name:\"marko\"])",
+ "anonymized": "g.mergeV(map0)",
+ "dotnet": "g.MergeV((IDictionary<object, object>) new Dictionary<object, object> {{ T.Label, new List<object> { \"person\", \"employee\" } }, { \"name\", \"marko\" }})",
+ "go": "g.MergeV(map[interface{}]interface{}{gremlingo.T.Label: []interface{}{\"person\", \"employee\"}, \"name\": \"marko\" })",
+ "groovy": "g.mergeV([(T.label):[\"person\", \"employee\"], name:\"marko\"])",
+ "java": "g.mergeV(new LinkedHashMap<Object, Object>() {{ put(T.label, new ArrayList<Object>() {{ add(\"person\"); add(\"employee\"); }}); put(\"name\", \"marko\"); }})",
+ "javascript": "g.mergeV(new Map([[T.label, [\"person\", \"employee\"]], [\"name\", \"marko\"]]))",
+ "python": "g.merge_v({ T.label: ['person', 'employee'], 'name': 'marko' })"
+ },
+ {
+ "original": "g.V()",
+ "language": "g.V()",
+ "canonical": "g.V()",
+ "anonymized": "g.V()",
+ "dotnet": "g.V()",
+ "go": "g.V()",
+ "groovy": "g.V()",
+ "java": "g.V()",
+ "javascript": "g.V()",
+ "python": "g.V()"
+ }
+ ]
+ },
+ {
+ "scenario": "g_mergeVXlabel_person_name_markoX_optionXonMatch_label_managerX",
+ "traversals": [
+ {
+ "original": "g.addV(\"person\").addLabel(\"employee\").property(\"name\", \"marko\")",
+ "language": "g.addV(\"person\").addLabel(\"employee\").property(\"name\", \"marko\")",
+ "canonical": "g.addV(\"person\").addLabel(\"employee\").property(\"name\", \"marko\")",
+ "anonymized": "g.addV(string0).addLabel(string1).property(string2, string3)",
+ "dotnet": "g.AddV((string) \"person\").AddLabel(\"employee\").Property(\"name\", \"marko\")",
+ "go": "g.AddV(\"person\").AddLabel(\"employee\").Property(\"name\", \"marko\")",
+ "groovy": "g.addV(\"person\").addLabel(\"employee\").property(\"name\", \"marko\")",
+ "java": "g.addV(\"person\").addLabel(\"employee\").property(\"name\", \"marko\")",
+ "javascript": "g.addV(\"person\").addLabel(\"employee\").property(\"name\", \"marko\")",
+ "python": "g.add_v('person').add_label('employee').property('name', 'marko')"
+ },
+ {
+ "original": "g.mergeV([(T.label): \"person\", name: \"marko\"]).option(Merge.onMatch, [(T.label): \"manager\"])",
+ "language": "g.mergeV([(T.label):\"person\", name:\"marko\"]).option(Merge.onMatch, [(T.label):\"manager\"])",
+ "canonical": "g.mergeV([(T.label):\"person\", name:\"marko\"]).option(Merge.onMatch, [(T.label):\"manager\"])",
+ "anonymized": "g.mergeV(map0).option(Merge.onMatch, map1)",
+ "dotnet": "g.MergeV((IDictionary<object, object>) new Dictionary<object, object> {{ T.Label, \"person\" }, { \"name\", \"marko\" }}).Option(Merge.OnMatch, (IDictionary<object, object>) new Dictionary<object, object> {{ T.Label, \"manager\" }})",
+ "go": "g.MergeV(map[interface{}]interface{}{gremlingo.T.Label: \"person\", \"name\": \"marko\" }).Option(gremlingo.Merge.OnMatch, map[interface{}]interface{}{gremlingo.T.Label: \"manager\" })",
+ "groovy": "g.mergeV([(T.label):\"person\", name:\"marko\"]).option(Merge.onMatch, [(T.label):\"manager\"])",
+ "java": "g.mergeV(new LinkedHashMap<Object, Object>() {{ put(T.label, \"person\"); put(\"name\", \"marko\"); }}).option(Merge.onMatch, new LinkedHashMap<Object, Object>() {{ put(T.label, \"manager\"); }})",
+ "javascript": "g.mergeV(new Map([[T.label, \"person\"], [\"name\", \"marko\"]])).option(Merge.onMatch, new Map([[T.label, \"manager\"]]))",
+ "python": "g.merge_v({ T.label: 'person', 'name': 'marko' }).option(Merge.on_match, { T.label: 'manager' })"
+ },
+ {
+ "original": "g.V()",
+ "language": "g.V()",
+ "canonical": "g.V()",
+ "anonymized": "g.V()",
+ "dotnet": "g.V()",
+ "go": "g.V()",
+ "groovy": "g.V()",
+ "java": "g.V()",
+ "javascript": "g.V()",
+ "python": "g.V()"
+ },
+ {
+ "original": "g.V().hasLabel(\"manager\")",
+ "language": "g.V().hasLabel(\"manager\")",
+ "canonical": "g.V().hasLabel(\"manager\")",
+ "anonymized": "g.V().hasLabel(string0)",
+ "dotnet": "g.V().HasLabel(\"manager\")",
+ "go": "g.V().HasLabel(\"manager\")",
+ "groovy": "g.V().hasLabel(\"manager\")",
+ "java": "g.V().hasLabel(\"manager\")",
+ "javascript": "g.V().hasLabel(\"manager\")",
+ "python": "g.V().has_label('manager')"
+ },
+ {
+ "original": "g.V().hasLabel(\"person\")",
+ "language": "g.V().hasLabel(\"person\")",
+ "canonical": "g.V().hasLabel(\"person\")",
+ "anonymized": "g.V().hasLabel(string0)",
+ "dotnet": "g.V().HasLabel(\"person\")",
+ "go": "g.V().HasLabel(\"person\")",
+ "groovy": "g.V().hasLabel(\"person\")",
+ "java": "g.V().hasLabel(\"person\")",
+ "javascript": "g.V().hasLabel(\"person\")",
+ "python": "g.V().has_label('person')"
+ },
+ {
+ "original": "g.V().hasLabel(\"employee\")",
+ "language": "g.V().hasLabel(\"employee\")",
+ "canonical": "g.V().hasLabel(\"employee\")",
+ "anonymized": "g.V().hasLabel(string0)",
+ "dotnet": "g.V().HasLabel(\"employee\")",
+ "go": "g.V().HasLabel(\"employee\")",
+ "groovy": "g.V().hasLabel(\"employee\")",
+ "java": "g.V().hasLabel(\"employee\")",
+ "javascript": "g.V().hasLabel(\"employee\")",
+ "python": "g.V().has_label('employee')"
+ }
+ ]
+ },
+ {
+ "scenario": "g_mergeVXlabel_person_name_markoX_optionXonMatch_label_manager_directorX",
+ "traversals": [
+ {
+ "original": "g.addV(\"person\").property(\"name\", \"marko\")",
+ "language": "g.addV(\"person\").property(\"name\", \"marko\")",
+ "canonical": "g.addV(\"person\").property(\"name\", \"marko\")",
+ "anonymized": "g.addV(string0).property(string1, string2)",
+ "dotnet": "g.AddV((string) \"person\").Property(\"name\", \"marko\")",
+ "go": "g.AddV(\"person\").Property(\"name\", \"marko\")",
+ "groovy": "g.addV(\"person\").property(\"name\", \"marko\")",
+ "java": "g.addV(\"person\").property(\"name\", \"marko\")",
+ "javascript": "g.addV(\"person\").property(\"name\", \"marko\")",
+ "python": "g.add_v('person').property('name', 'marko')"
+ },
+ {
+ "original": "g.mergeV([(T.label): \"person\", name: \"marko\"]).option(Merge.onMatch, [(T.label): [\"manager\",\"director\"]])",
+ "language": "g.mergeV([(T.label):\"person\", name:\"marko\"]).option(Merge.onMatch, [(T.label):[\"manager\", \"director\"]])",
+ "canonical": "g.mergeV([(T.label):\"person\", name:\"marko\"]).option(Merge.onMatch, [(T.label):[\"manager\", \"director\"]])",
+ "anonymized": "g.mergeV(map0).option(Merge.onMatch, map1)",
+ "dotnet": "g.MergeV((IDictionary<object, object>) new Dictionary<object, object> {{ T.Label, \"person\" }, { \"name\", \"marko\" }}).Option(Merge.OnMatch, (IDictionary<object, object>) new Dictionary<object, object> {{ T.Label, new List<object> { \"manager\", \"director\" } }})",
+ "go": "g.MergeV(map[interface{}]interface{}{gremlingo.T.Label: \"person\", \"name\": \"marko\" }).Option(gremlingo.Merge.OnMatch, map[interface{}]interface{}{gremlingo.T.Label: []interface{}{\"manager\", \"director\"} })",
+ "groovy": "g.mergeV([(T.label):\"person\", name:\"marko\"]).option(Merge.onMatch, [(T.label):[\"manager\", \"director\"]])",
+ "java": "g.mergeV(new LinkedHashMap<Object, Object>() {{ put(T.label, \"person\"); put(\"name\", \"marko\"); }}).option(Merge.onMatch, new LinkedHashMap<Object, Object>() {{ put(T.label, new ArrayList<Object>() {{ add(\"manager\"); add(\"director\"); }}); }})",
+ "javascript": "g.mergeV(new Map([[T.label, \"person\"], [\"name\", \"marko\"]])).option(Merge.onMatch, new Map([[T.label, [\"manager\", \"director\"]]]))",
+ "python": "g.merge_v({ T.label: 'person', 'name': 'marko' }).option(Merge.on_match, { T.label: ['manager', 'director'] })"
+ },
+ {
+ "original": "g.V()",
+ "language": "g.V()",
+ "canonical": "g.V()",
+ "anonymized": "g.V()",
+ "dotnet": "g.V()",
+ "go": "g.V()",
+ "groovy": "g.V()",
+ "java": "g.V()",
+ "javascript": "g.V()",
+ "python": "g.V()"
+ },
+ {
+ "original": "g.V().hasLabel(\"manager\").hasLabel(\"director\")",
+ "language": "g.V().hasLabel(\"manager\").hasLabel(\"director\")",
+ "canonical": "g.V().hasLabel(\"manager\").hasLabel(\"director\")",
+ "anonymized": "g.V().hasLabel(string0).hasLabel(string1)",
+ "dotnet": "g.V().HasLabel(\"manager\").HasLabel(\"director\")",
+ "go": "g.V().HasLabel(\"manager\").HasLabel(\"director\")",
+ "groovy": "g.V().hasLabel(\"manager\").hasLabel(\"director\")",
+ "java": "g.V().hasLabel(\"manager\").hasLabel(\"director\")",
+ "javascript": "g.V().hasLabel(\"manager\").hasLabel(\"director\")",
+ "python": "g.V().has_label('manager').has_label('director')"
+ },
+ {
+ "original": "g.V().hasLabel(\"person\")",
+ "language": "g.V().hasLabel(\"person\")",
+ "canonical": "g.V().hasLabel(\"person\")",
+ "anonymized": "g.V().hasLabel(string0)",
+ "dotnet": "g.V().HasLabel(\"person\")",
+ "go": "g.V().HasLabel(\"person\")",
+ "groovy": "g.V().hasLabel(\"person\")",
+ "java": "g.V().hasLabel(\"person\")",
+ "javascript": "g.V().hasLabel(\"person\")",
+ "python": "g.V().has_label('person')"
+ }
+ ]
+ },
+ {
+ "scenario": "g_mergeVXlabel_person_name_markoX_optionXonMatch_label_emptyX",
+ "traversals": [
+ {
+ "original": "g.addV(\"person\").property(\"name\", \"marko\")",
+ "language": "g.addV(\"person\").property(\"name\", \"marko\")",
+ "canonical": "g.addV(\"person\").property(\"name\", \"marko\")",
+ "anonymized": "g.addV(string0).property(string1, string2)",
+ "dotnet": "g.AddV((string) \"person\").Property(\"name\", \"marko\")",
+ "go": "g.AddV(\"person\").Property(\"name\", \"marko\")",
+ "groovy": "g.addV(\"person\").property(\"name\", \"marko\")",
+ "java": "g.addV(\"person\").property(\"name\", \"marko\")",
+ "javascript": "g.addV(\"person\").property(\"name\", \"marko\")",
+ "python": "g.add_v('person').property('name', 'marko')"
+ },
+ {
+ "original": "g.mergeV([(T.label): \"person\", name: \"marko\"]).option(Merge.onMatch, [(T.label): []])",
+ "language": "g.mergeV([(T.label):\"person\", name:\"marko\"]).option(Merge.onMatch, [(T.label):[]])",
+ "canonical": "g.mergeV([(T.label):\"person\", name:\"marko\"]).option(Merge.onMatch, [(T.label):[]])",
+ "anonymized": "g.mergeV(map0).option(Merge.onMatch, map1)",
+ "dotnet": "g.MergeV((IDictionary<object, object>) new Dictionary<object, object> {{ T.Label, \"person\" }, { \"name\", \"marko\" }}).Option(Merge.OnMatch, (IDictionary<object, object>) new Dictionary<object, object> {{ T.Label, new List<object> { } }})",
+ "go": "g.MergeV(map[interface{}]interface{}{gremlingo.T.Label: \"person\", \"name\": \"marko\" }).Option(gremlingo.Merge.OnMatch, map[interface{}]interface{}{gremlingo.T.Label: []interface{}{} })",
+ "groovy": "g.mergeV([(T.label):\"person\", name:\"marko\"]).option(Merge.onMatch, [(T.label):[]])",
+ "java": "g.mergeV(new LinkedHashMap<Object, Object>() {{ put(T.label, \"person\"); put(\"name\", \"marko\"); }}).option(Merge.onMatch, new LinkedHashMap<Object, Object>() {{ put(T.label, new ArrayList<Object>() {{ }}); }})",
+ "javascript": "g.mergeV(new Map([[T.label, \"person\"], [\"name\", \"marko\"]])).option(Merge.onMatch, new Map([[T.label, []]]))",
+ "python": "g.merge_v({ T.label: 'person', 'name': 'marko' }).option(Merge.on_match, { T.label: [] })"
+ },
+ {
+ "original": "g.V()",
+ "language": "g.V()",
+ "canonical": "g.V()",
+ "anonymized": "g.V()",
+ "dotnet": "g.V()",
+ "go": "g.V()",
+ "groovy": "g.V()",
+ "java": "g.V()",
+ "javascript": "g.V()",
+ "python": "g.V()"
+ },
+ {
+ "original": "g.V().hasLabel(\"vertex\")",
+ "language": "g.V().hasLabel(\"vertex\")",
+ "canonical": "g.V().hasLabel(\"vertex\")",
+ "anonymized": "g.V().hasLabel(string0)",
+ "dotnet": "g.V().HasLabel(\"vertex\")",
+ "go": "g.V().HasLabel(\"vertex\")",
+ "groovy": "g.V().hasLabel(\"vertex\")",
+ "java": "g.V().hasLabel(\"vertex\")",
+ "javascript": "g.V().hasLabel(\"vertex\")",
+ "python": "g.V().has_label('vertex')"
+ },
+ {
+ "original": "g.V().hasLabel(\"person\")",
+ "language": "g.V().hasLabel(\"person\")",
+ "canonical": "g.V().hasLabel(\"person\")",
+ "anonymized": "g.V().hasLabel(string0)",
+ "dotnet": "g.V().HasLabel(\"person\")",
+ "go": "g.V().HasLabel(\"person\")",
+ "groovy": "g.V().hasLabel(\"person\")",
+ "java": "g.V().hasLabel(\"person\")",
+ "javascript": "g.V().hasLabel(\"person\")",
+ "python": "g.V().has_label('person')"
+ }
+ ]
+ },
{
"scenario": "g_V_age_min",
"traversals": [
@@ -41231,6 +41870,105 @@
}
]
},
+ {
+ "scenario": "g_V_hasLabelXpersonX_hasXname_markoX_addLabelXemployeeX_labels",
+ "traversals": [
+ {
+ "original": "g.addV(\"person\").property(\"name\", \"marko\")",
+ "language": "g.addV(\"person\").property(\"name\", \"marko\")",
+ "canonical": "g.addV(\"person\").property(\"name\", \"marko\")",
+ "anonymized": "g.addV(string0).property(string1, string2)",
+ "dotnet": "g.AddV((string) \"person\").Property(\"name\", \"marko\")",
+ "go": "g.AddV(\"person\").Property(\"name\", \"marko\")",
+ "groovy": "g.addV(\"person\").property(\"name\", \"marko\")",
+ "java": "g.addV(\"person\").property(\"name\", \"marko\")",
+ "javascript": "g.addV(\"person\").property(\"name\", \"marko\")",
+ "python": "g.add_v('person').property('name', 'marko')"
+ },
+ {
+ "original": "g.V().hasLabel(\"person\").has(\"name\", \"marko\").addLabel(\"employee\").labels().fold()",
+ "language": "g.V().hasLabel(\"person\").has(\"name\", \"marko\").addLabel(\"employee\").labels().fold()",
+ "canonical": "g.V().hasLabel(\"person\").has(\"name\", \"marko\").addLabel(\"employee\").labels().fold()",
+ "anonymized": "g.V().hasLabel(string0).has(string1, string2).addLabel(string3).labels().fold()",
+ "dotnet": "g.V().HasLabel(\"person\").Has(\"name\", \"marko\").AddLabel(\"employee\").Labels().Fold()",
+ "go": "g.V().HasLabel(\"person\").Has(\"name\", \"marko\").AddLabel(\"employee\").Labels().Fold()",
+ "groovy": "g.V().hasLabel(\"person\").has(\"name\", \"marko\").addLabel(\"employee\").labels().fold()",
+ "java": "g.V().hasLabel(\"person\").has(\"name\", \"marko\").addLabel(\"employee\").labels().fold()",
+ "javascript": "g.V().hasLabel(\"person\").has(\"name\", \"marko\").addLabel(\"employee\").labels().fold()",
+ "python": "g.V().has_label('person').has('name', 'marko').add_label('employee').labels().fold()"
+ },
+ {
+ "original": "g.V().hasLabel(\"person\").hasLabel(\"employee\")",
+ "language": "g.V().hasLabel(\"person\").hasLabel(\"employee\")",
+ "canonical": "g.V().hasLabel(\"person\").hasLabel(\"employee\")",
+ "anonymized": "g.V().hasLabel(string0).hasLabel(string1)",
+ "dotnet": "g.V().HasLabel(\"person\").HasLabel(\"employee\")",
+ "go": "g.V().HasLabel(\"person\").HasLabel(\"employee\")",
+ "groovy": "g.V().hasLabel(\"person\").hasLabel(\"employee\")",
+ "java": "g.V().hasLabel(\"person\").hasLabel(\"employee\")",
+ "javascript": "g.V().hasLabel(\"person\").hasLabel(\"employee\")",
+ "python": "g.V().has_label('person').has_label('employee')"
+ }
+ ]
+ },
+ {
+ "scenario": "g_V_addLabelXa_bX_labels_count",
+ "traversals": [
+ {
+ "original": "g.addV(\"person\")",
+ "language": "g.addV(\"person\")",
+ "canonical": "g.addV(\"person\")",
+ "anonymized": "g.addV(string0)",
+ "dotnet": "g.AddV((string) \"person\")",
+ "go": "g.AddV(\"person\")",
+ "groovy": "g.addV(\"person\")",
+ "java": "g.addV(\"person\")",
+ "javascript": "g.addV(\"person\")",
+ "python": "g.add_v('person')"
+ },
+ {
+ "original": "g.V().addLabel(\"a\", \"b\").labels().count()",
+ "language": "g.V().addLabel(\"a\", \"b\").labels().count()",
+ "canonical": "g.V().addLabel(\"a\", \"b\").labels().count()",
+ "anonymized": "g.V().addLabel(string0, string1).labels().count()",
+ "dotnet": "g.V().AddLabel(\"a\", \"b\").Labels().Count()",
+ "go": "g.V().AddLabel(\"a\", \"b\").Labels().Count()",
+ "groovy": "g.V().addLabel(\"a\", \"b\").labels().count()",
+ "java": "g.V().addLabel(\"a\", \"b\").labels().count()",
+ "javascript": "g.V().addLabel(\"a\", \"b\").labels().count()",
+ "python": "g.V().add_label('a', 'b').labels().count()"
+ }
+ ]
+ },
+ {
+ "scenario": "g_V_addLabelXexistingX_labels_count",
+ "traversals": [
+ {
+ "original": "g.addV(\"person\")",
+ "language": "g.addV(\"person\")",
+ "canonical": "g.addV(\"person\")",
+ "anonymized": "g.addV(string0)",
+ "dotnet": "g.AddV((string) \"person\")",
+ "go": "g.AddV(\"person\")",
+ "groovy": "g.addV(\"person\")",
+ "java": "g.addV(\"person\")",
+ "javascript": "g.addV(\"person\")",
+ "python": "g.add_v('person')"
+ },
+ {
+ "original": "g.V().addLabel(\"person\").labels().count()",
+ "language": "g.V().addLabel(\"person\").labels().count()",
+ "canonical": "g.V().addLabel(\"person\").labels().count()",
+ "anonymized": "g.V().addLabel(string0).labels().count()",
+ "dotnet": "g.V().AddLabel(\"person\").Labels().Count()",
+ "go": "g.V().AddLabel(\"person\").Labels().Count()",
+ "groovy": "g.V().addLabel(\"person\").labels().count()",
+ "java": "g.V().addLabel(\"person\").labels().count()",
+ "javascript": "g.V().addLabel(\"person\").labels().count()",
+ "python": "g.V().add_label('person').labels().count()"
+ }
+ ]
+ },
{
"scenario": "g_V_valueXnameX_aggregateXxX_capXxX",
"traversals": [
@@ -42200,6 +42938,146 @@
}
]
},
+ {
+ "scenario": "g_V_dropLabelXaX_labels",
+ "traversals": [
+ {
+ "original": "g.addV(\"a\", \"b\")",
+ "language": "g.addV(\"a\", \"b\")",
+ "canonical": "g.addV(\"a\", \"b\")",
+ "anonymized": "g.addV(string0, string1)",
+ "dotnet": "g.AddV((string) \"a\", (string) \"b\")",
+ "go": "g.AddV(\"a\", \"b\")",
+ "groovy": "g.addV(\"a\", \"b\")",
+ "java": "g.addV(\"a\", \"b\")",
+ "javascript": "g.addV(\"a\", \"b\")",
+ "python": "g.add_v('a', 'b')"
+ },
+ {
+ "original": "g.V().dropLabel(\"a\").labels().fold()",
+ "language": "g.V().dropLabel(\"a\").labels().fold()",
+ "canonical": "g.V().dropLabel(\"a\").labels().fold()",
+ "anonymized": "g.V().dropLabel(string0).labels().fold()",
+ "dotnet": "g.V().DropLabel(\"a\").Labels().Fold()",
+ "go": "g.V().DropLabel(\"a\").Labels().Fold()",
+ "groovy": "g.V().dropLabel(\"a\").labels().fold()",
+ "java": "g.V().dropLabel(\"a\").labels().fold()",
+ "javascript": "g.V().dropLabel(\"a\").labels().fold()",
+ "python": "g.V().drop_label('a').labels().fold()"
+ },
+ {
+ "original": "g.V().hasLabel(\"a\")",
+ "language": "g.V().hasLabel(\"a\")",
+ "canonical": "g.V().hasLabel(\"a\")",
+ "anonymized": "g.V().hasLabel(string0)",
+ "dotnet": "g.V().HasLabel(\"a\")",
+ "go": "g.V().HasLabel(\"a\")",
+ "groovy": "g.V().hasLabel(\"a\")",
+ "java": "g.V().hasLabel(\"a\")",
+ "javascript": "g.V().hasLabel(\"a\")",
+ "python": "g.V().has_label('a')"
+ },
+ {
+ "original": "g.V().hasLabel(\"b\")",
+ "language": "g.V().hasLabel(\"b\")",
+ "canonical": "g.V().hasLabel(\"b\")",
+ "anonymized": "g.V().hasLabel(string0)",
+ "dotnet": "g.V().HasLabel(\"b\")",
+ "go": "g.V().HasLabel(\"b\")",
+ "groovy": "g.V().hasLabel(\"b\")",
+ "java": "g.V().hasLabel(\"b\")",
+ "javascript": "g.V().hasLabel(\"b\")",
+ "python": "g.V().has_label('b')"
+ }
+ ]
+ },
+ {
+ "scenario": "g_V_dropLabels_labels",
+ "traversals": [
+ {
+ "original": "g.addV(\"a\", \"b\")",
+ "language": "g.addV(\"a\", \"b\")",
+ "canonical": "g.addV(\"a\", \"b\")",
+ "anonymized": "g.addV(string0, string1)",
+ "dotnet": "g.AddV((string) \"a\", (string) \"b\")",
+ "go": "g.AddV(\"a\", \"b\")",
+ "groovy": "g.addV(\"a\", \"b\")",
+ "java": "g.addV(\"a\", \"b\")",
+ "javascript": "g.addV(\"a\", \"b\")",
+ "python": "g.add_v('a', 'b')"
+ },
+ {
+ "original": "g.V().dropLabels().labels()",
+ "language": "g.V().dropLabels().labels()",
+ "canonical": "g.V().dropLabels().labels()",
+ "anonymized": "g.V().dropLabels().labels()",
+ "dotnet": "g.V().DropLabels().Labels()",
+ "go": "g.V().DropLabels().Labels()",
+ "groovy": "g.V().dropLabels().labels()",
+ "java": "g.V().dropLabels().labels()",
+ "javascript": "g.V().dropLabels().labels()",
+ "python": "g.V().drop_labels().labels()"
+ }
+ ]
+ },
+ {
+ "scenario": "g_V_dropLabelXa_bX_labels",
+ "traversals": [
+ {
+ "original": "g.addV(\"a\", \"b\", \"c\")",
+ "language": "g.addV(\"a\", \"b\", \"c\")",
+ "canonical": "g.addV(\"a\", \"b\", \"c\")",
+ "anonymized": "g.addV(string0, string1, string2)",
+ "dotnet": "g.AddV((string) \"a\", (string) \"b\", (string) \"c\")",
+ "go": "g.AddV(\"a\", \"b\", \"c\")",
+ "groovy": "g.addV(\"a\", \"b\", \"c\")",
+ "java": "g.addV(\"a\", \"b\", \"c\")",
+ "javascript": "g.addV(\"a\", \"b\", \"c\")",
+ "python": "g.add_v('a', 'b', 'c')"
+ },
+ {
+ "original": "g.V().dropLabel(\"a\", \"b\").labels()",
+ "language": "g.V().dropLabel(\"a\", \"b\").labels()",
+ "canonical": "g.V().dropLabel(\"a\", \"b\").labels()",
+ "anonymized": "g.V().dropLabel(string0, string1).labels()",
+ "dotnet": "g.V().DropLabel(\"a\", \"b\").Labels()",
+ "go": "g.V().DropLabel(\"a\", \"b\").Labels()",
+ "groovy": "g.V().dropLabel(\"a\", \"b\").labels()",
+ "java": "g.V().dropLabel(\"a\", \"b\").labels()",
+ "javascript": "g.V().dropLabel(\"a\", \"b\").labels()",
+ "python": "g.V().drop_label('a', 'b').labels()"
+ }
+ ]
+ },
+ {
+ "scenario": "g_V_dropLabels_defaultLabel",
+ "traversals": [
+ {
+ "original": "g.addV(\"person\")",
+ "language": "g.addV(\"person\")",
+ "canonical": "g.addV(\"person\")",
+ "anonymized": "g.addV(string0)",
+ "dotnet": "g.AddV((string) \"person\")",
+ "go": "g.AddV(\"person\")",
+ "groovy": "g.addV(\"person\")",
+ "java": "g.addV(\"person\")",
+ "javascript": "g.addV(\"person\")",
+ "python": "g.add_v('person')"
+ },
+ {
+ "original": "g.V().dropLabels().labels()",
+ "language": "g.V().dropLabels().labels()",
+ "canonical": "g.V().dropLabels().labels()",
+ "anonymized": "g.V().dropLabels().labels()",
+ "dotnet": "g.V().DropLabels().Labels()",
+ "go": "g.V().DropLabels().Labels()",
+ "groovy": "g.V().dropLabels().labels()",
+ "java": "g.V().dropLabels().labels()",
+ "javascript": "g.V().dropLabels().labels()",
+ "python": "g.V().drop_labels().labels()"
+ }
+ ]
+ },
{
"scenario": "g_V_fail",
"traversals": [
diff --git a/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/test/features/map/AddVertex.feature b/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/test/features/map/AddVertex.feature
index 99e1492f56..0d7fdaf2c7 100644
--- a/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/test/features/map/AddVertex.feature
+++ b/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/test/features/map/AddVertex.feature
@@ -703,4 +703,27 @@ Feature: Step - addV()
When iterated to list
Then the result should be unordered
| result |
- | d[2010].i |
\ No newline at end of file
+ | d[2010].i |
+
+ @MultiLabel
+ Scenario: g_addVXa_bX_labels
+ Given the empty graph
+ And the traversal of
+ """
+ g.addV("a", "b").labels().fold()
+ """
+ When iterated to list
+ Then the result should have a count of 1
+ And the graph should return 1 for count of "g.V().hasLabel(\"a\").hasLabel(\"b\")"
+
+ @MultiLabel
+ Scenario: g_addVXa_b_cX_labels_count
+ Given the empty graph
+ And the traversal of
+ """
+ g.addV("a", "b", "c").labels().count()
+ """
+ When iterated to list
+ Then the result should be unordered
+ | result |
+ | d[3].l |
diff --git a/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/test/features/map/Labels.feature b/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/test/features/map/Labels.feature
new file mode 100644
index 0000000000..322d0ca42c
--- /dev/null
+++ b/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/test/features/map/Labels.feature
@@ -0,0 +1,110 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+@StepClassMap @StepLabels @MultiLabel
+Feature: Step - labels()
+
+ @MultiLabel
+ Scenario: g_V_hasLabelXpersonX_labels
+ Given the modern graph
+ And the traversal of
+ """
+ g.V().hasLabel("person").labels()
+ """
+ When iterated to list
+ Then the result should be unordered
+ | result |
+ | person |
+ | person |
+ | person |
+ | person |
+
+ @MultiLabel
+ Scenario: g_addVXa_bX_labels
+ Given the empty graph
+ And the graph initializer of
+ """
+ g.addV("a", "b")
+ """
+ And the traversal of
+ """
+ g.V().labels()
+ """
+ When iterated to list
+ Then the result should be unordered
+ | result |
+ | a |
+ | b |
+
+ @MultiLabel
+ Scenario: g_addVXa_bX_labels_fold
+ Given the empty graph
+ And the graph initializer of
+ """
+ g.addV("a", "b")
+ """
+ And the traversal of
+ """
+ g.V().labels().fold()
+ """
+ When iterated to list
+ Then the result should have a count of 1
+
+ @MultiLabel
+ Scenario: g_addVXa_bX_labels_count
+ Given the empty graph
+ And the graph initializer of
+ """
+ g.addV("a", "b")
+ """
+ And the traversal of
+ """
+ g.V().labels().count()
+ """
+ When iterated to list
+ Then the result should be unordered
+ | result |
+ | d[2].l |
+
+ @MultiLabel
+ Scenario: g_addV_labels
+ Given the empty graph
+ And the graph initializer of
+ """
+ g.addV()
+ """
+ And the traversal of
+ """
+ g.V().labels()
+ """
+ When iterated to list
+ Then the result should be unordered
+ | result |
+ | vertex |
+
+ @MultiLabel
+ Scenario: g_E_labels
+ Given the modern graph
+ And the traversal of
+ """
+ g.E().hasLabel("knows").labels()
+ """
+ When iterated to list
+ Then the result should be unordered
+ | result |
+ | knows |
+ | knows |
diff --git a/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/test/features/map/MergeVertex.feature b/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/test/features/map/MergeVertex.feature
index 801b39db7f..930e3a181b 100644
--- a/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/test/features/map/MergeVertex.feature
+++ b/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/test/features/map/MergeVertex.feature
@@ -990,3 +990,127 @@ Feature: Step - mergeV()
Then the result should have a count of 1
And the graph should return 1 for count of "g.V().has(\"person\",\"name\",\"stephen\").hasNot(\"created\")"
And the graph should return 2 for count of "g.V()"
+
+ @MultiLabel
+ Scenario: g_mergeVXlabel_ab_name_markoX_multilabel_create
+ Given the empty graph
+ And the traversal of
+ """
+ g.mergeV([(T.label): ["person","employee"], name: "marko"])
+ """
+ When iterated to list
+ Then the result should have a count of 1
+ And the graph should return 1 for count of "g.V()"
+ And the graph should return 1 for count of "g.V().hasLabel(\"person\").hasLabel(\"employee\")"
+ And the graph should return 1 for count of "g.V().has(\"name\",\"marko\")"
+
+ @MultiLabel
+ Scenario: g_mergeVXlabel_abc_name_testX_multilabel_create
+ Given the empty graph
+ And the traversal of
+ """
+ g.mergeV([(T.label): ["a","b","c"], name: "test"])
+ """
+ When iterated to list
+ Then the result should have a count of 1
+ And the graph should return 1 for count of "g.V()"
+ And the graph should return 1 for count of "g.V().hasLabel(\"a\").hasLabel(\"b\").hasLabel(\"c\")"
+
+ @MultiLabel
+ Scenario: g_mergeVXlabel_person_name_markoX_single_label
+ Given the empty graph
+ And the traversal of
+ """
+ g.mergeV([(T.label): "person", name: "marko"])
+ """
+ When iterated to list
+ Then the result should have a count of 1
+ And the graph should return 1 for count of "g.V()"
+ And the graph should return 1 for count of "g.V().hasLabel(\"person\")"
+ And the graph should return 1 for count of "g.V().has(\"name\",\"marko\")"
+
+ @MultiLabel
+ Scenario: g_mergeVXlabel_ab_name_markoX_multilabel_match
+ Given the empty graph
+ And the graph initializer of
+ """
+ g.addV("person").addLabel("employee").property("name", "marko")
+ """
+ And the traversal of
+ """
+ g.mergeV([(T.label): ["person","employee"], name: "marko"])
+ """
+ When iterated to list
+ Then the result should have a count of 1
+ And the graph should return 1 for count of "g.V()"
+ And the graph should return 1 for count of "g.V().hasLabel(\"person\").hasLabel(\"employee\")"
+
+ @MultiLabel
+ Scenario: g_mergeVXlabel_ab_name_markoX_multilabel_nomatch
+ Given the empty graph
+ And the graph initializer of
+ """
+ g.addV("person").property("name", "marko")
+ """
+ And the traversal of
+ """
+ g.mergeV([(T.label): ["person","employee"], name: "marko"])
+ """
+ When iterated to list
+ Then the result should have a count of 1
+ And the graph should return 2 for count of "g.V()"
+
+ @MultiLabel
+ Scenario: g_mergeVXlabel_person_name_markoX_optionXonMatch_label_managerX
+ Given the empty graph
+ And the graph initializer of
+ """
+ g.addV("person").addLabel("employee").property("name", "marko")
+ """
+ And the traversal of
+ """
+ g.mergeV([(T.label): "person", name: "marko"]).
+ option(Merge.onMatch, [(T.label): "manager"])
+ """
+ When iterated to list
+ Then the result should have a count of 1
+ And the graph should return 1 for count of "g.V()"
+ And the graph should return 1 for count of "g.V().hasLabel(\"manager\")"
+ And the graph should return 0 for count of "g.V().hasLabel(\"person\")"
+ And the graph should return 0 for count of "g.V().hasLabel(\"employee\")"
+
+ @MultiLabel
+ Scenario: g_mergeVXlabel_person_name_markoX_optionXonMatch_label_manager_directorX
+ Given the empty graph
+ And the graph initializer of
+ """
+ g.addV("person").property("name", "marko")
+ """
+ And the traversal of
+ """
+ g.mergeV([(T.label): "person", name: "marko"]).
+ option(Merge.onMatch, [(T.label): ["manager","director"]])
+ """
+ When iterated to list
+ Then the result should have a count of 1
+ And the graph should return 1 for count of "g.V()"
+ And the graph should return 1 for count of "g.V().hasLabel(\"manager\").hasLabel(\"director\")"
+ And the graph should return 0 for count of "g.V().hasLabel(\"person\")"
+
+ @MultiLabel
+ Scenario: g_mergeVXlabel_person_name_markoX_optionXonMatch_label_emptyX
+ Given the empty graph
+ And the graph initializer of
+ """
+ g.addV("person").property("name", "marko")
+ """
+ And the traversal of
+ """
+ g.mergeV([(T.label): "person", name: "marko"]).
+ option(Merge.onMatch, [(T.label): []])
+ """
+ When iterated to list
+ Then the result should have a count of 1
+ And the graph should return 1 for count of "g.V()"
+ And the graph should return 1 for count of "g.V().hasLabel(\"vertex\")"
+ And the graph should return 0 for count of "g.V().hasLabel(\"person\")"
diff --git a/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/test/features/sideEffect/AddLabel.feature b/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/test/features/sideEffect/AddLabel.feature
new file mode 100644
index 0000000000..821b80ab72
--- /dev/null
+++ b/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/test/features/sideEffect/AddLabel.feature
@@ -0,0 +1,66 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+@StepClassSideEffect @StepAddLabel @MultiLabel
+Feature: Step - addLabel()
+
+ @MultiLabel
+ Scenario: g_V_hasLabelXpersonX_hasXname_markoX_addLabelXemployeeX_labels
+ Given the empty graph
+ And the graph initializer of
+ """
+ g.addV("person").property("name", "marko")
+ """
+ And the traversal of
+ """
+ g.V().hasLabel("person").has("name", "marko").addLabel("employee").labels().fold()
+ """
+ When iterated to list
+ Then the result should have a count of 1
+ And the graph should return 1 for count of "g.V().hasLabel(\"person\").hasLabel(\"employee\")"
+
+ @MultiLabel
+ Scenario: g_V_addLabelXa_bX_labels_count
+ Given the empty graph
+ And the graph initializer of
+ """
+ g.addV("person")
+ """
+ And the traversal of
+ """
+ g.V().addLabel("a", "b").labels().count()
+ """
+ When iterated to list
+ Then the result should be unordered
+ | result |
+ | d[3].l |
+
+ @MultiLabel
+ Scenario: g_V_addLabelXexistingX_labels_count
+ Given the empty graph
+ And the graph initializer of
+ """
+ g.addV("person")
+ """
+ And the traversal of
+ """
+ g.V().addLabel("person").labels().count()
+ """
+ When iterated to list
+ Then the result should be unordered
+ | result |
+ | d[1].l |
diff --git a/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/test/features/sideEffect/DropLabel.feature b/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/test/features/sideEffect/DropLabel.feature
new file mode 100644
index 0000000000..051cc793af
--- /dev/null
+++ b/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/test/features/sideEffect/DropLabel.feature
@@ -0,0 +1,83 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+@StepClassSideEffect @StepDropLabel @MultiLabel
+Feature: Step - dropLabel() / dropLabels()
+
+ @MultiLabel
+ Scenario: g_V_dropLabelXaX_labels
+ Given the empty graph
+ And the graph initializer of
+ """
+ g.addV("a", "b")
+ """
+ And the traversal of
+ """
+ g.V().dropLabel("a").labels().fold()
+ """
+ When iterated to list
+ Then the result should have a count of 1
+ And the graph should return 0 for count of "g.V().hasLabel(\"a\")"
+ And the graph should return 1 for count of "g.V().hasLabel(\"b\")"
+
+ @MultiLabel
+ Scenario: g_V_dropLabels_labels
+ Given the empty graph
+ And the graph initializer of
+ """
+ g.addV("a", "b")
+ """
+ And the traversal of
+ """
+ g.V().dropLabels().labels()
+ """
+ When iterated to list
+ Then the result should be unordered
+ | result |
+ | vertex |
+
+ @MultiLabel
+ Scenario: g_V_dropLabelXa_bX_labels
+ Given the empty graph
+ And the graph initializer of
+ """
+ g.addV("a", "b", "c")
+ """
+ And the traversal of
+ """
+ g.V().dropLabel("a", "b").labels()
+ """
+ When iterated to list
+ Then the result should be unordered
+ | result |
+ | c |
+
+ @MultiLabel
+ Scenario: g_V_dropLabels_defaultLabel
+ Given the empty graph
+ And the graph initializer of
+ """
+ g.addV("person")
+ """
+ And the traversal of
+ """
+ g.V().dropLabels().labels()
+ """
+ When iterated to list
+ Then the result should be unordered
+ | result |
+ | vertex |
diff --git a/gremlin-test/src/test/java/org/apache/tinkerpop/gremlin/structure/ExceptionCoverageTest.java b/gremlin-test/src/test/java/org/apache/tinkerpop/gremlin/structure/ExceptionCoverageTest.java
index a8f3946128..17b8b020dc 100644
--- a/gremlin-test/src/test/java/org/apache/tinkerpop/gremlin/structure/ExceptionCoverageTest.java
+++ b/gremlin-test/src/test/java/org/apache/tinkerpop/gremlin/structure/ExceptionCoverageTest.java
@@ -75,6 +75,9 @@ public class ExceptionCoverageTest {
add("org.apache.tinkerpop.gremlin.structure.Element$Exceptions#elementAlreadyRemoved"); // as of 3.1.0
add("org.apache.tinkerpop.gremlin.structure.Graph$Exceptions#traversalEngineNotSupported"); // as of 3.2.0
+ // this is a general default exception for providers that don't support label mutation:
+ add("org.apache.tinkerpop.gremlin.structure.Element$Exceptions#labelMutationNotSupported");
+
// need to write consistency tests for the following items still...........
add("org.apache.tinkerpop.gremlin.process.computer.GraphComputer$Exceptions#supportsDirectObjects");
}};
diff --git a/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/AbstractTinkerGraph.java b/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/AbstractTinkerGraph.java
index a77edac34d..5a0abb6d13 100644
--- a/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/AbstractTinkerGraph.java
+++ b/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/AbstractTinkerGraph.java
@@ -354,6 +354,26 @@ public abstract class AbstractTinkerGraph implements Graph {
protected abstract void addInEdge(final TinkerVertex vertex, final String label, final Edge edge);
+ /**
+ * Add an edge to the per-vertex adjacency maps under the given label.
+ * Used when labels are added to an existing edge.
+ *
+ * @param edge the edge to register
+ * @param label the label under which to register the edge
+ * @since 4.0.0
+ */
+ public abstract void addEdgeToAdjacency(final TinkerEdge edge, final String label);
+
+ /**
+ * Remove an edge from the per-vertex adjacency maps for the given label.
+ * Used when labels are removed from an existing edge.
+ *
+ * @param edge the edge to unregister
+ * @param label the label from which to unregister the edge
+ * @since 4.0.0
+ */
+ public abstract void removeEdgeFromAdjacency(final TinkerEdge edge, final String label);
+
/**
* Called when a vertex's labels are modified to allow the graph to update any internal label indices.
* The default implementation is a no-op since TinkerGraph does not maintain a separate label index.
diff --git a/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerEdge.java b/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerEdge.java
index 3ced83454e..663908af0e 100644
--- a/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerEdge.java
+++ b/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerEdge.java
@@ -30,6 +30,7 @@ import org.apache.tinkerpop.gremlin.util.iterator.IteratorUtils;
import java.util.Collections;
import java.util.Iterator;
+import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
@@ -40,6 +41,7 @@ import java.util.stream.Collectors;
*/
public class TinkerEdge extends TinkerElement implements Edge {
+ protected final Set<String> edgeLabels;
protected Map<String, Property> properties;
protected Vertex inVertex = null;
@@ -62,8 +64,30 @@ public class TinkerEdge extends TinkerElement implements Edge {
}
}
+ protected TinkerEdge(final Object id, final Vertex outVertex, final Set<String> labels, final Vertex inVertex) {
+ this(id, outVertex, labels, inVertex, 0);
+ }
+
+ protected TinkerEdge(final Object id, final Vertex outVertex, final Set<String> labels, final Vertex inVertex, final long currentVersion) {
+ this(id, (AbstractTinkerGraph) outVertex.graph(), outVertex.id(),
+ (labels == null || labels.isEmpty()) ? Edge.DEFAULT_LABEL : labels.iterator().next(),
+ inVertex.id(), currentVersion, false);
+ this.edgeLabels.clear();
+ if (labels != null && !labels.isEmpty()) {
+ this.edgeLabels.addAll(labels);
+ } else {
+ this.edgeLabels.add(Edge.DEFAULT_LABEL);
+ }
+ if (!isTxMode) {
+ this.inVertex = inVertex;
+ this.outVertex = outVertex;
+ }
+ }
+
private TinkerEdge(final Object id, AbstractTinkerGraph graph, final Object outVertexId, final String label, final Object inVertexId, final long currentVersion, final Boolean skipIndexUpdate) {
super(id, label, currentVersion);
+ this.edgeLabels = ConcurrentHashMap.newKeySet();
+ this.edgeLabels.add(label);
isTxMode = graph instanceof TinkerTransactionGraph;
this.graph = graph;
if (isTxMode) {
@@ -107,7 +131,66 @@ public class TinkerEdge extends TinkerElement implements Edge {
@Override
public Set<String> labels() {
- return Collections.singleton(this.label);
+ return Collections.unmodifiableSet(this.edgeLabels);
+ }
+
+ @Override
+ @Deprecated
+ public String label() {
+ return this.edgeLabels.iterator().next();
+ }
+
+ @Override
+ public void addLabel(final String label, final String... labels) {
+ graph.touch(this);
+ ElementHelper.validateLabel(label);
+ for (final String l : labels) {
+ ElementHelper.validateLabel(l);
+ }
+ // Remove default label if it was the only label
+ if (this.edgeLabels.size() == 1 && this.edgeLabels.contains(Edge.DEFAULT_LABEL)) {
+ this.graph.removeEdgeFromAdjacency(this, Edge.DEFAULT_LABEL);
+ this.edgeLabels.remove(Edge.DEFAULT_LABEL);
+ }
+ this.edgeLabels.add(label);
+ this.graph.addEdgeToAdjacency(this, label);
+ for (final String l : labels) {
+ this.edgeLabels.add(l);
+ this.graph.addEdgeToAdjacency(this, l);
+ }
+ this.label = this.edgeLabels.iterator().next();
+ }
+
+ @Override
+ public void dropLabels() {
+ graph.touch(this);
+ for (final String l : new LinkedHashSet<>(this.edgeLabels)) {
+ this.graph.removeEdgeFromAdjacency(this, l);
+ }
+ this.edgeLabels.clear();
+ this.edgeLabels.add(Edge.DEFAULT_LABEL);
+ this.graph.addEdgeToAdjacency(this, Edge.DEFAULT_LABEL);
+ this.label = this.edgeLabels.iterator().next();
+ }
+
+ @Override
+ public void dropLabel(final String label, final String... labels) {
+ graph.touch(this);
+ if (this.edgeLabels.contains(label)) {
+ this.graph.removeEdgeFromAdjacency(this, label);
+ this.edgeLabels.remove(label);
+ }
+ for (final String l : labels) {
+ if (this.edgeLabels.contains(l)) {
+ this.graph.removeEdgeFromAdjacency(this, l);
+ this.edgeLabels.remove(l);
+ }
+ }
+ if (this.edgeLabels.isEmpty()) {
+ this.edgeLabels.add(Edge.DEFAULT_LABEL);
+ this.graph.addEdgeToAdjacency(this, Edge.DEFAULT_LABEL);
+ }
+ this.label = this.edgeLabels.iterator().next();
}
@Override
@@ -129,11 +212,15 @@ public class TinkerEdge extends TinkerElement implements Edge {
if (!isTxMode) {
// shallow copy for non-tx mode
final TinkerEdge edge = new TinkerEdge(id, outVertex, label, inVertex, currentVersion);
+ edge.edgeLabels.clear();
+ edge.edgeLabels.addAll(this.edgeLabels);
edge.properties = properties;
return edge;
}
final TinkerEdge edge = new TinkerEdge(id, graph, outVertexId, label, inVertexId, currentVersion, true);
+ edge.edgeLabels.clear();
+ edge.edgeLabels.addAll(this.edgeLabels);
if (properties != null) {
final Map<String, Property> cloned = new ConcurrentHashMap<>(properties.size());
diff --git a/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerElement.java b/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerElement.java
index 8aa2d1db03..d8587b71fa 100644
--- a/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerElement.java
+++ b/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerElement.java
@@ -27,7 +27,7 @@ import org.apache.tinkerpop.gremlin.structure.util.ElementHelper;
public abstract class TinkerElement implements Element {
protected final Object id;
- protected final String label;
+ protected String label;
protected boolean removed = false;
protected long currentVersion;
diff --git a/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerGraph.java b/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerGraph.java
index ffe328f98e..3b493caa5d 100644
--- a/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerGraph.java
+++ b/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerGraph.java
@@ -330,6 +330,36 @@ public class TinkerGraph extends AbstractTinkerGraph {
edges.add(edge);
}
+ @Override
+ public void addEdgeToAdjacency(final TinkerEdge edge, final String label) {
+ final TinkerVertex outV = (TinkerVertex) edge.outVertex();
+ final TinkerVertex inV = (TinkerVertex) edge.inVertex();
+ if (null == outV.outEdges) outV.outEdges = new HashMap<>();
+ outV.outEdges.computeIfAbsent(label, k -> new HashSet<>()).add(edge);
+ if (null == inV.inEdges) inV.inEdges = new HashMap<>();
+ inV.inEdges.computeIfAbsent(label, k -> new HashSet<>()).add(edge);
+ }
+
+ @Override
+ public void removeEdgeFromAdjacency(final TinkerEdge edge, final String label) {
+ final TinkerVertex outV = (TinkerVertex) edge.outVertex();
+ final TinkerVertex inV = (TinkerVertex) edge.inVertex();
+ if (outV.outEdges != null) {
+ final Set<Edge> edges = outV.outEdges.get(label);
+ if (edges != null) {
+ edges.remove(edge);
+ if (edges.isEmpty()) outV.outEdges.remove(label);
+ }
+ }
+ if (inV.inEdges != null) {
+ final Set<Edge> edges = inV.inEdges.get(label);
+ if (edges != null) {
+ edges.remove(edge);
+ if (edges.isEmpty()) inV.inEdges.remove(label);
+ }
+ }
+ }
+
/**
* Return TinkerGraph feature set.
* <p/>
diff --git a/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerTransactionGraph.java b/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerTransactionGraph.java
index d7914981d5..a223607fe2 100644
--- a/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerTransactionGraph.java
+++ b/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerTransactionGraph.java
@@ -139,7 +139,8 @@ public final class TinkerTransactionGraph extends AbstractTinkerGraph {
Object idValue = vertexIdManager.convert(ElementHelper.getIdValue(keyValues).orElse(null));
if (null == idValue)
idValue = vertexIdManager.getNextId(this);
- final String label = ElementHelper.getLabelValue(keyValues).orElse(Vertex.DEFAULT_LABEL);
+ final Set<String> labels = ElementHelper.getLabelsValue(keyValues).orElse(
+ Collections.singleton(Vertex.DEFAULT_LABEL));
this.tx().readWrite();
final long txNumber = transaction.getTxNumber();
@@ -164,7 +165,7 @@ public final class TinkerTransactionGraph extends AbstractTinkerGraph {
if (container == null)
container = newContainer;
- final TinkerVertex vertex = new TinkerVertex(idValue, label, this, version);
+ final TinkerVertex vertex = new TinkerVertex(idValue, labels, this, version);
ElementHelper.attachProperties(vertex, VertexProperty.Cardinality.list, keyValues);
container.setDraft(vertex, (TinkerTransaction) tx());
@@ -410,6 +411,40 @@ public final class TinkerTransactionGraph extends AbstractTinkerGraph {
edges.add(edge.id());
}
+ @Override
+ public void addEdgeToAdjacency(final TinkerEdge edge, final String label) {
+ final TinkerVertex outV = (TinkerVertex) edge.outVertex();
+ final TinkerVertex inV = (TinkerVertex) edge.inVertex();
+ touch(outV);
+ touch(inV);
+ if (null == outV.outEdgesId) outV.outEdgesId = new ConcurrentHashMap<>();
+ outV.outEdgesId.computeIfAbsent(label, k -> ConcurrentHashMap.newKeySet()).add(edge.id());
+ if (null == inV.inEdgesId) inV.inEdgesId = new ConcurrentHashMap<>();
+ inV.inEdgesId.computeIfAbsent(label, k -> ConcurrentHashMap.newKeySet()).add(edge.id());
+ }
+
+ @Override
+ public void removeEdgeFromAdjacency(final TinkerEdge edge, final String label) {
+ final TinkerVertex outV = (TinkerVertex) edge.outVertex();
+ final TinkerVertex inV = (TinkerVertex) edge.inVertex();
+ touch(outV);
+ touch(inV);
+ if (outV.outEdgesId != null) {
+ final Set<Object> edges = outV.outEdgesId.get(label);
+ if (edges != null) {
+ edges.remove(edge.id());
+ if (edges.isEmpty()) outV.outEdgesId.remove(label);
+ }
+ }
+ if (inV.inEdgesId != null) {
+ final Set<Object> edges = inV.inEdgesId.get(label);
+ if (edges != null) {
+ edges.remove(edge.id());
+ if (edges.isEmpty()) inV.inEdgesId.remove(label);
+ }
+ }
+ }
+
/**
* Return TinkerGraph feature set.
* <p/>
diff --git a/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerVertex.java b/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerVertex.java
index b10ebe1e7b..457db2cc94 100644
--- a/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerVertex.java
+++ b/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerVertex.java
@@ -61,36 +61,32 @@ public class TinkerVertex extends TinkerElement implements Vertex {
protected final Set<String> vertexLabels;
protected TinkerVertex(final Object id, final String label, final AbstractTinkerGraph graph) {
- super(id, label);
- this.graph = graph;
- this.isTxMode = graph instanceof TinkerTransactionGraph;
- this.allowNullPropertyValues = graph.features().vertex().supportsNullPropertyValues();
- this.vertexLabels = ConcurrentHashMap.newKeySet();
- this.vertexLabels.add(null == label ? Vertex.DEFAULT_LABEL : label);
+ this(id, Collections.singleton(label != null ? label : Vertex.DEFAULT_LABEL), graph, -1);
}
protected TinkerVertex(final Object id, final String label, final AbstractTinkerGraph graph, final long currentVersion) {
- super(id, label, currentVersion);
- this.graph = graph;
- this.isTxMode = graph instanceof TinkerTransactionGraph;
- this.allowNullPropertyValues = graph.features().vertex().supportsNullPropertyValues();
- this.vertexLabels = ConcurrentHashMap.newKeySet();
- this.vertexLabels.add(null == label ? Vertex.DEFAULT_LABEL : label);
+ this(id, Collections.singleton(label != null ? label : Vertex.DEFAULT_LABEL), graph, currentVersion);
}
/**
* Constructs a TinkerVertex with multiple labels.
*/
protected TinkerVertex(final Object id, final Set<String> labels, final AbstractTinkerGraph graph) {
- super(id, (labels == null || labels.isEmpty()) ? Vertex.DEFAULT_LABEL : labels.iterator().next());
+ this(id, labels, graph, -1);
+ }
+
+ /**
+ * Canonical constructor. Constructs a TinkerVertex with multiple labels and a specific version (for transactional graphs).
+ */
+ protected TinkerVertex(final Object id, final Set<String> labels, final AbstractTinkerGraph graph, final long currentVersion) {
+ super(id, (labels == null || labels.isEmpty()) ? Vertex.DEFAULT_LABEL : labels.iterator().next(), currentVersion);
this.graph = graph;
this.isTxMode = graph instanceof TinkerTransactionGraph;
this.allowNullPropertyValues = graph.features().vertex().supportsNullPropertyValues();
+ this.vertexLabels = ConcurrentHashMap.newKeySet();
if (labels == null || labels.isEmpty()) {
- this.vertexLabels = ConcurrentHashMap.newKeySet();
this.vertexLabels.add(Vertex.DEFAULT_LABEL);
} else {
- this.vertexLabels = ConcurrentHashMap.newKeySet();
this.vertexLabels.addAll(labels);
}
}
@@ -120,6 +116,7 @@ public class TinkerVertex extends TinkerElement implements Vertex {
this.vertexLabels.add(label);
Collections.addAll(this.vertexLabels, labels);
+ this.label = this.vertexLabels.iterator().next();
this.graph.updateVertexLabelIndex(this);
}
@@ -127,6 +124,7 @@ public class TinkerVertex extends TinkerElement implements Vertex {
public void dropLabels() {
this.vertexLabels.clear();
this.vertexLabels.add(Vertex.DEFAULT_LABEL);
+ this.label = this.vertexLabels.iterator().next();
this.graph.updateVertexLabelIndex(this);
}
@@ -140,6 +138,7 @@ public class TinkerVertex extends TinkerElement implements Vertex {
if (this.vertexLabels.isEmpty()) {
this.vertexLabels.add(Vertex.DEFAULT_LABEL);
}
+ this.label = this.vertexLabels.iterator().next();
this.graph.updateVertexLabelIndex(this);
}
@@ -153,9 +152,7 @@ public class TinkerVertex extends TinkerElement implements Vertex {
return vertex;
}
- final TinkerVertex vertex = new TinkerVertex(id, label, graph, currentVersion);
- vertex.vertexLabels.clear();
- vertex.vertexLabels.addAll(this.vertexLabels);
+ final TinkerVertex vertex = new TinkerVertex(id, new LinkedHashSet<>(vertexLabels), graph, currentVersion);
if (inEdgesId != null)
vertex.inEdgesId = CollectionUtil.clone((ConcurrentHashMap<String, Set<Object>>) inEdgesId);
diff --git a/tinkergraph-gremlin/src/test/java/org/apache/tinkerpop/gremlin/tinkergraph/process/traversal/step/sideEffect/LabelMutationStepTest.java b/tinkergraph-gremlin/src/test/java/org/apache/tinkerpop/gremlin/tinkergraph/process/traversal/step/sideEffect/LabelMutationStepTest.java
index 58ff4fbce1..7ac5c88015 100644
--- a/tinkergraph-gremlin/src/test/java/org/apache/tinkerpop/gremlin/tinkergraph/process/traversal/step/sideEffect/LabelMutationStepTest.java
+++ b/tinkergraph-gremlin/src/test/java/org/apache/tinkerpop/gremlin/tinkergraph/process/traversal/step/sideEffect/LabelMutationStepTest.java
@@ -78,12 +78,14 @@ public class LabelMutationStepTest {
assertThat(v.labels(), containsInAnyOrder("person", "manager"));
}
- @Test(expected = UnsupportedOperationException.class)
- public void shouldThrowWhenAddingLabelToEdgeViaTraversal() {
+ @Test
+ public void shouldAddLabelToEdgeViaTraversal() {
final Vertex v1 = g.addV("person").next();
final Vertex v2 = g.addV("person").next();
- v1.addEdge("knows", v2);
+ final Edge e = v1.addEdge("knows", v2);
g.E().addLabel("friend").iterate();
+ assertThat(e.labels(), hasSize(2));
+ assertThat(e.labels(), containsInAnyOrder("knows", "friend"));
}
// --- dropLabel step tests ---
@@ -112,12 +114,14 @@ public class LabelMutationStepTest {
assertThat(v.labels(), containsInAnyOrder("employee"));
}
- @Test(expected = UnsupportedOperationException.class)
- public void shouldThrowWhenDroppingLabelsOnEdgeViaTraversal() {
+ @Test
+ public void shouldDropLabelsOnEdgeViaTraversal() {
final Vertex v1 = g.addV("person").next();
final Vertex v2 = g.addV("person").next();
- v1.addEdge("knows", v2);
+ final Edge e = v1.addEdge("knows", v2);
g.E().dropLabels().iterate();
+ assertThat(e.labels(), hasSize(1));
+ assertThat(e.labels(), containsInAnyOrder(Edge.DEFAULT_LABEL));
}
// --- addV multi-label tests ---
diff --git a/tinkergraph-gremlin/src/test/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerVertexMultiLabelTest.java b/tinkergraph-gremlin/src/test/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerVertexMultiLabelTest.java
index 5fc84f8de2..27387d60e9 100644
--- a/tinkergraph-gremlin/src/test/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerVertexMultiLabelTest.java
+++ b/tinkergraph-gremlin/src/test/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerVertexMultiLabelTest.java
@@ -147,20 +147,24 @@ public class TinkerVertexMultiLabelTest {
assertThat(v.labels(), containsInAnyOrder(Vertex.DEFAULT_LABEL));
}
- @Test(expected = UnsupportedOperationException.class)
- public void shouldThrowWhenAddingLabelToEdge() {
+ @Test
+ public void shouldAddLabelToEdge() {
final Vertex v1 = g.addV("person").next();
final Vertex v2 = g.addV("person").next();
final Edge e = v1.addEdge("knows", v2);
e.addLabel("friend");
+ assertThat(e.labels(), hasSize(2));
+ assertThat(e.labels(), containsInAnyOrder("knows", "friend"));
}
- @Test(expected = UnsupportedOperationException.class)
- public void shouldThrowWhenDroppingLabelsOnEdge() {
+ @Test
+ public void shouldDropLabelsOnEdge() {
final Vertex v1 = g.addV("person").next();
final Vertex v2 = g.addV("person").next();
final Edge e = v1.addEdge("knows", v2);
e.dropLabels();
+ assertThat(e.labels(), hasSize(1));
+ assertThat(e.labels(), containsInAnyOrder(Edge.DEFAULT_LABEL));
}
@Test
(tinkerpop) 04/05: Add cardinality support and append-only update for multi-label
Posted by xi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
xiazcy pushed a commit to branch multi-label-experiment
in repository https://gitbox.apache.org/repos/asf/tinkerpop.git
commit 6a1e99ee33c1b87165e407f40298ca7614087e7a
Author: Yang Xia <xi...@gmail.com>
AuthorDate: Thu Jun 25 02:18:51 2026 -0700
Add cardinality support and append-only update for multi-label
- Introduce LabelCardinality enum as pure data descriptor (min/max/mutable fields)
- Add LabelCardinalityValidator for separated constraint enforcement
- Add Graph.Features for label cardinality support
- Update MergeVertex/MergeEdge to use append-only label semantics on merge
- Simplify with('multilabel') to source-level only (remove redundant step-level path)
- Add serialization support across GraphML, GraphSON v1/v2/v3, Gryo, GraphBinary
- Add label replace pattern validation tests
- Update GLV test translations for cardinality scenarios
---
.../grammar/DefaultGremlinBaseVisitor.java | 4 -
.../language/grammar/TraversalMethodVisitor.java | 19 --
.../grammar/TraversalSourceSpawnMethodVisitor.java | 26 +-
.../process/traversal/step/map/AddVertexStep.java | 15 +-
.../process/traversal/step/map/ElementMapStep.java | 12 +-
.../process/traversal/step/map/MergeEdgeStep.java | 6 +-
.../traversal/step/map/MergeVertexStep.java | 6 +-
.../traversal/step/map/PropertyMapStep.java | 8 +-
.../process/traversal/step/util/WithOptions.java | 7 +-
.../apache/tinkerpop/gremlin/structure/Graph.java | 44 ++++
.../gremlin/structure/LabelCardinality.java | 85 +++++++
.../structure/io/binary/types/EdgeSerializer.java | 15 +-
.../structure/io/binary/types/GraphSerializer.java | 6 +-
.../io/binary/types/VertexSerializer.java | 6 +-
.../structure/io/graphml/GraphMLWriter.java | 6 +-
.../io/graphson/GraphSONSerializersV1.java | 8 +-
.../io/graphson/GraphSONSerializersV2.java | 8 +-
.../io/graphson/GraphSONSerializersV3.java | 8 +-
.../structure/io/gryo/GryoSerializersV3.java | 10 +-
.../structure/util/LabelCardinalityValidator.java | 104 ++++++++
.../gremlin/structure/util/star/StarGraph.java | 14 +-
.../Gremlin.Net.IntegrationTest/Gherkin/Gremlin.cs | 5 +-
gremlin-go/driver/cucumber/gremlin.go | 5 +-
.../gremlin-javascript/test/cucumber/gremlin.js | 5 +-
gremlin-language/src/main/antlr4/Gremlin.g4 | 2 -
.../src/main/python/tests/feature/gremlin.py | 5 +-
.../gremlin/language/translator/translations.json | 182 ++------------
.../gremlin/test/features/map/AddEdge.feature | 32 ---
.../gremlin/test/features/map/MergeVertex.feature | 9 +-
.../test/features/sideEffect/AddLabel.feature | 4 +-
.../test/features/sideEffect/DropLabel.feature | 18 +-
.../ser/binary/TypeSerializerFailureTests.java | 7 +-
.../tinkergraph/structure/AbstractTinkerGraph.java | 27 +++
.../gremlin/tinkergraph/structure/TinkerEdge.java | 44 +---
.../gremlin/tinkergraph/structure/TinkerGraph.java | 10 +-
.../structure/TinkerTransactionGraph.java | 10 +-
.../tinkergraph/structure/TinkerVertex.java | 78 ++++--
.../traversal/step/map/MergeVMultiLabelTest.java | 27 ++-
.../step/sideEffect/LabelMutationPropertyTest.java | 19 +-
.../step/sideEffect/LabelMutationStepTest.java | 76 ++++--
.../LabelReplacePatternValidationTest.java | 264 +++++++++++++++++++++
.../structure/TinkerVertexMultiLabelTest.java | 34 +--
42 files changed, 830 insertions(+), 450 deletions(-)
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/language/grammar/DefaultGremlinBaseVisitor.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/language/grammar/DefaultGremlinBaseVisitor.java
index 02fa82e925..9bde0d2ddf 100644
--- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/language/grammar/DefaultGremlinBaseVisitor.java
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/language/grammar/DefaultGremlinBaseVisitor.java
@@ -167,10 +167,6 @@ public class DefaultGremlinBaseVisitor<T> extends AbstractParseTreeVisitor<T> im
* {@inheritDoc}
*/
@Override public T visitTraversalMethod_addE_String(final GremlinParser.TraversalMethod_addE_StringContext ctx) { notImplemented(ctx); return null; }
- /**
- * {@inheritDoc}
- */
- @Override public T visitTraversalMethod_addE_StringVarargs(final GremlinParser.TraversalMethod_addE_StringVarargsContext ctx) { notImplemented(ctx); return null; }
/**
* {@inheritDoc}
*/
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/language/grammar/TraversalMethodVisitor.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/language/grammar/TraversalMethodVisitor.java
index f99ce7f4b8..f54f04c73f 100644
--- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/language/grammar/TraversalMethodVisitor.java
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/language/grammar/TraversalMethodVisitor.java
@@ -205,25 +205,6 @@ public class TraversalMethodVisitor extends TraversalRootVisitor<GraphTraversal>
}
}
- /**
- * {@inheritDoc}
- */
- @Override
- public GraphTraversal visitTraversalMethod_addE_StringVarargs(final GremlinParser.TraversalMethod_addE_StringVarargsContext ctx) {
- final List<GremlinParser.StringArgumentContext> args = ctx.stringArgument();
- final Object firstLiteralOrVar = antlr.argumentVisitor.visitStringArgument(args.get(0));
- final String firstLabel = firstLiteralOrVar instanceof String ? (String) firstLiteralOrVar : ((GValue<String>) firstLiteralOrVar).get();
- final Object secondLiteralOrVar = antlr.argumentVisitor.visitStringArgument(args.get(1));
- final String secondLabel = secondLiteralOrVar instanceof String ? (String) secondLiteralOrVar : ((GValue<String>) secondLiteralOrVar).get();
-
- final String[] moreLabels = new String[args.size() - 2];
- for (int i = 2; i < args.size(); i++) {
- final Object literalOrVar = antlr.argumentVisitor.visitStringArgument(args.get(i));
- moreLabels[i - 2] = literalOrVar instanceof String ? (String) literalOrVar : ((GValue<String>) literalOrVar).get();
- }
- return this.graphTraversal.addE(firstLabel, secondLabel, moreLabels);
- }
-
/**
* {@inheritDoc}
*/
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/language/grammar/TraversalSourceSpawnMethodVisitor.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/language/grammar/TraversalSourceSpawnMethodVisitor.java
index c07c1b21b9..903f3f9d2b 100644
--- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/language/grammar/TraversalSourceSpawnMethodVisitor.java
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/language/grammar/TraversalSourceSpawnMethodVisitor.java
@@ -57,27 +57,13 @@ public class TraversalSourceSpawnMethodVisitor extends DefaultGremlinBaseVisitor
*/
@Override
public GraphTraversal visitTraversalSourceSpawnMethod_addE(final GremlinParser.TraversalSourceSpawnMethod_addEContext ctx) {
- final List<GremlinParser.StringArgumentContext> stringArgs = ctx.stringArgument();
- if (stringArgs != null && !stringArgs.isEmpty()) {
- if (stringArgs.size() == 1) {
- final Object literalOrVar = antlr.argumentVisitor.visitStringArgument(stringArgs.get(0));
- if (GValue.valueInstanceOf(literalOrVar, String.class)) {
- return this.traversalSource.addE((GValue<String>) literalOrVar);
- } else {
- return this.traversalSource.addE((String) literalOrVar);
- }
+ final GremlinParser.StringArgumentContext stringArg = ctx.stringArgument();
+ if (stringArg != null) {
+ final Object literalOrVar = antlr.argumentVisitor.visitStringArgument(stringArg);
+ if (GValue.valueInstanceOf(literalOrVar, String.class)) {
+ return this.traversalSource.addE((GValue<String>) literalOrVar);
} else {
- // Multi-label: addE("a", "b", ...)
- final Object firstLiteralOrVar = antlr.argumentVisitor.visitStringArgument(stringArgs.get(0));
- final String firstLabel = firstLiteralOrVar instanceof String ? (String) firstLiteralOrVar : ((GValue<String>) firstLiteralOrVar).get();
- final Object secondLiteralOrVar = antlr.argumentVisitor.visitStringArgument(stringArgs.get(1));
- final String secondLabel = secondLiteralOrVar instanceof String ? (String) secondLiteralOrVar : ((GValue<String>) secondLiteralOrVar).get();
- final String[] moreLabels = new String[stringArgs.size() - 2];
- for (int i = 2; i < stringArgs.size(); i++) {
- final Object literalOrVar = antlr.argumentVisitor.visitStringArgument(stringArgs.get(i));
- moreLabels[i - 2] = literalOrVar instanceof String ? (String) literalOrVar : ((GValue<String>) literalOrVar).get();
- }
- return this.traversalSource.addE(firstLabel, secondLabel, moreLabels);
+ return this.traversalSource.addE((String) literalOrVar);
}
} else if (ctx.nestedTraversal() != null) {
return this.traversalSource.addE(anonymousVisitor.visitNestedTraversal(ctx.nestedTraversal()));
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/AddVertexStep.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/AddVertexStep.java
index 4c2b505b53..8a48d1728b 100644
--- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/AddVertexStep.java
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/AddVertexStep.java
@@ -49,24 +49,27 @@ public class AddVertexStep<S> extends ScalarMapStep<S, Vertex> implements AddVer
public AddVertexStep(final Traversal.Admin traversal, final String label) {
super(traversal);
- this.internalParameters.set(this, T.label, null == label ? Vertex.DEFAULT_LABEL : label);
+ if (label != null) {
+ this.internalParameters.set(this, T.label, label);
+ }
userProvidedLabel = label != null;
}
public AddVertexStep(final Traversal.Admin traversal, final Traversal.Admin<S,String> vertexLabelTraversal) {
super(traversal);
- this.internalParameters.set(this, T.label, null == vertexLabelTraversal ? Vertex.DEFAULT_LABEL : vertexLabelTraversal);
+ if (vertexLabelTraversal != null) {
+ this.internalParameters.set(this, T.label, vertexLabelTraversal);
+ }
userProvidedLabel = vertexLabelTraversal != null;
}
public AddVertexStep(final Traversal.Admin traversal, final Set<String> labels) {
super(traversal);
- if (labels == null || labels.isEmpty()) {
- this.internalParameters.set(this, T.label, Vertex.DEFAULT_LABEL);
- userProvidedLabel = false;
- } else {
+ if (labels != null && !labels.isEmpty()) {
this.internalParameters.set(this, T.label, labels);
userProvidedLabel = true;
+ } else {
+ userProvidedLabel = false;
}
}
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/ElementMapStep.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/ElementMapStep.java
index b05e620849..68b7ede062 100644
--- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/ElementMapStep.java
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/ElementMapStep.java
@@ -53,7 +53,6 @@ public class ElementMapStep<K,E> extends ScalarMapStep<Element, Map<K, E>> imple
protected final String[] propertyKeys;
private boolean onGraphComputer = false;
- private boolean multilabel = false;
private final Parameters parameters = new Parameters();
public ElementMapStep(final Traversal.Admin traversal, final String... propertyKeys) {
@@ -63,11 +62,7 @@ public class ElementMapStep<K,E> extends ScalarMapStep<Element, Map<K, E>> imple
@Override
public void configure(final Object... keyValues) {
- if (keyValues[0].equals(WithOptions.multilabel)) {
- this.multilabel = true;
- } else {
- this.parameters.set(this, keyValues);
- }
+ this.parameters.set(this, keyValues);
}
@Override
@@ -126,11 +121,10 @@ public class ElementMapStep<K,E> extends ScalarMapStep<Element, Map<K, E>> imple
}
/**
- * Checks if multilabel mode is enabled either via step-level {@code .with(WithOptions.multilabel)}
- * or source-level {@code g.with("multilabel")}.
+ * Checks if multilabel mode is enabled via source-level {@code g.with("multilabel")}.
*/
private boolean isMultilabelEnabled() {
- return WithOptions.isMultilabelEnabled(this.multilabel, getTraversal());
+ return WithOptions.isMultilabelEnabled(getTraversal());
}
public String[] getPropertyKeys() {
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/MergeEdgeStep.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/MergeEdgeStep.java
index 261ab78eb8..9bc4e59f78 100644
--- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/MergeEdgeStep.java
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/MergeEdgeStep.java
@@ -315,10 +315,9 @@ public class MergeEdgeStep<S> extends MergeElementStep<S, Edge, Map<Object, Obje
validateMapInput(onMatchMap, true);
onMatchMap.forEach((key, value) -> {
- // Handle T.label replacement for multi-label support
+ // Handle T.label for multi-label support: append only (addLabel semantics)
+ // No label removal via onMatch — follows cardinality exceptions
if (T.label.equals(key) || T.label.getAccessor().equals(key)) {
- // Drop all existing labels and replace with new ones
- e.dropLabels();
if (value instanceof String) {
e.addLabel((String) value);
} else if (value instanceof java.util.Collection) {
@@ -330,7 +329,6 @@ public class MergeEdgeStep<S> extends MergeElementStep<S, Edge, Map<Object, Obje
e.addLabel(labelArray[0],
Arrays.copyOfRange(labelArray, 1, labelArray.length));
}
- // Empty collection = use default label behavior (already handled by dropLabels())
}
return;
}
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/MergeVertexStep.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/MergeVertexStep.java
index ad37175cd3..3434c5e1cd 100644
--- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/MergeVertexStep.java
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/MergeVertexStep.java
@@ -103,10 +103,9 @@ public class MergeVertexStep<S> extends MergeElementStep<S, Vertex, Map<Object,
validateMapInput(onMatchMap, true);
onMatchMap.forEach((key, value) -> {
- // Handle T.label replacement for multi-label support
+ // Handle T.label for multi-label support: append only (addLabel semantics)
+ // No label removal via onMatch — follows cardinality exceptions
if (T.label.equals(key) || T.label.getAccessor().equals(key)) {
- // Drop all existing labels and replace with new ones
- v.dropLabels();
if (value instanceof String) {
v.addLabel((String) value);
} else if (value instanceof java.util.Collection) {
@@ -118,7 +117,6 @@ public class MergeVertexStep<S> extends MergeElementStep<S, Vertex, Map<Object,
v.addLabel(labelArray[0],
java.util.Arrays.copyOfRange(labelArray, 1, labelArray.length));
}
- // Empty collection = use default label behavior (already handled by dropLabels())
}
return;
}
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/PropertyMapStep.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/PropertyMapStep.java
index 665ea10e4b..74ad26886a 100644
--- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/PropertyMapStep.java
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/PropertyMapStep.java
@@ -58,7 +58,6 @@ public class PropertyMapStep<K,E> extends ScalarMapStep<Element, Map<K, E>>
protected int tokens;
protected Traversal.Admin<Element, ? extends Property> propertyTraversal;
- protected boolean multilabel = false;
protected Parameters parameters = new Parameters();
protected Traversal.Admin<K, E> valueTraversal;
@@ -98,8 +97,6 @@ public class PropertyMapStep<K,E> extends ScalarMapStep<Element, Map<K, E>>
this.tokens |= (int) keyValues[i];
}
}
- } else if (keyValues[0].equals(WithOptions.multilabel)) {
- this.multilabel = true;
} else {
this.parameters.set(this, keyValues);
}
@@ -215,11 +212,10 @@ public class PropertyMapStep<K,E> extends ScalarMapStep<Element, Map<K, E>>
}
/**
- * Checks if multilabel mode is enabled either via step-level {@code .with(WithOptions.multilabel)}
- * or source-level {@code g.with("multilabel")}.
+ * Checks if multilabel mode is enabled via source-level {@code g.with("multilabel")}.
*/
private boolean isMultilabelEnabled() {
- return WithOptions.isMultilabelEnabled(this.multilabel, getTraversal());
+ return WithOptions.isMultilabelEnabled(getTraversal());
}
protected Object getElementId(Element element){
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/util/WithOptions.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/util/WithOptions.java
index dd139ca7ba..7c599dd924 100644
--- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/util/WithOptions.java
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/util/WithOptions.java
@@ -121,11 +121,10 @@ public class WithOptions {
public static final String MULTILABEL_KEY = "multilabel";
/**
- * Checks whether multi-label output is enabled for the given traversal, either at the step level
- * (via step-level configuration) or at the source level (via {@code g.with("multilabel")}).
+ * Checks whether multi-label output is enabled for the given traversal via source-level
+ * {@code g.with("multilabel")} configuration.
*/
- public static boolean isMultilabelEnabled(final boolean stepLevelEnabled, final Traversal.Admin<?, ?> traversal) {
- if (stepLevelEnabled) return true;
+ public static boolean isMultilabelEnabled(final Traversal.Admin<?, ?> traversal) {
return traversal.getStrategies().getStrategy(OptionsStrategy.class)
.map(os -> os.getOptions().containsKey(MULTILABEL_KEY) || os.getOptions().containsKey(multilabel))
.orElse(false);
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/Graph.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/Graph.java
index 4d064c1df2..d0453be36c 100644
--- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/Graph.java
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/Graph.java
@@ -737,6 +737,28 @@ public interface Graph extends AutoCloseable, Host {
return new VertexPropertyFeatures() {
};
}
+
+ /**
+ * Gets the {@link LabelCardinality} for vertices in this graph. Defines how many labels
+ * a vertex can have and whether labels are mutable.
+ *
+ * @return the label cardinality for vertices, defaulting to {@link LabelCardinality#ZERO_OR_MORE}
+ * @since 4.0.0
+ */
+ default LabelCardinality getLabelCardinality() {
+ return LabelCardinality.ZERO_OR_MORE;
+ }
+
+ /**
+ * Gets the default label returned for vertices with no explicit labels when the cardinality
+ * requires at least one label ({@link LabelCardinality#ONE} or {@link LabelCardinality#ONE_OR_MORE}).
+ *
+ * @return the default vertex label, typically {@link Vertex#DEFAULT_LABEL}
+ * @since 4.0.0
+ */
+ default String getDefaultLabel() {
+ return Vertex.DEFAULT_LABEL;
+ }
}
/**
@@ -785,6 +807,28 @@ public interface Graph extends AutoCloseable, Host {
return new EdgePropertyFeatures() {
};
}
+
+ /**
+ * Gets the {@link LabelCardinality} for edges in this graph. Defines how many labels
+ * an edge can have and whether labels are mutable.
+ *
+ * @return the label cardinality for edges, defaulting to {@link LabelCardinality#ZERO_OR_ONE}
+ * @since 4.0.0
+ */
+ default LabelCardinality getLabelCardinality() {
+ return LabelCardinality.ZERO_OR_ONE;
+ }
+
+ /**
+ * Gets the default label returned for edges with no explicit labels when the cardinality
+ * requires at least one label ({@link LabelCardinality#ONE} or {@link LabelCardinality#ONE_OR_MORE}).
+ *
+ * @return the default edge label, typically {@link Edge#DEFAULT_LABEL}
+ * @since 4.0.0
+ */
+ default String getDefaultLabel() {
+ return Edge.DEFAULT_LABEL;
+ }
}
/**
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/LabelCardinality.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/LabelCardinality.java
new file mode 100644
index 0000000000..f8a80799f3
--- /dev/null
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/LabelCardinality.java
@@ -0,0 +1,85 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tinkerpop.gremlin.structure;
+
+/**
+ * Defines the label cardinality for graph elements. Each value declares its multiplicity constraints
+ * via {@link #min()} and {@link #max()}, and whether mutation is permitted via {@link #supportsMutation()}.
+ * <p>
+ * Providers declare their supported cardinality via {@link Graph.Features}.
+ * Validation of label operations against these constraints is handled by
+ * {@link org.apache.tinkerpop.gremlin.structure.util.LabelCardinalityValidator}.
+ *
+ * @since 4.0.0
+ */
+public enum LabelCardinality {
+
+ /**
+ * Exactly one label, immutable. All mutation operations throw.
+ * This is the default for TinkerGraph and provides backward compatibility with TinkerPop 3.x.
+ */
+ ONE(1, 1, false),
+
+ /**
+ * One or more labels. The element must always have at least one label.
+ * {@code dropLabels()} always throws. {@code dropLabel(x)} succeeds only if at least one label remains.
+ */
+ ONE_OR_MORE(1, Integer.MAX_VALUE, true),
+
+ /**
+ * Zero or more labels, fully flexible. No constraints on the number of labels.
+ * Elements can have any number of labels including zero.
+ */
+ ZERO_OR_MORE(0, Integer.MAX_VALUE, true);
+
+ private final int min;
+ private final int max;
+ private final boolean mutable;
+
+ LabelCardinality(final int min, final int max, final boolean mutable) {
+ this.min = min;
+ this.max = max;
+ this.mutable = mutable;
+ }
+
+ /**
+ * The minimum number of labels an element must have under this cardinality.
+ */
+ public int min() { return min; }
+
+ /**
+ * The maximum number of labels an element may have under this cardinality.
+ */
+ public int max() { return max; }
+
+ /**
+ * Whether this cardinality allows multiple labels on an element simultaneously.
+ */
+ public boolean supportsMultiLabel() { return max > 1; }
+
+ /**
+ * Whether this cardinality allows an element to have zero labels.
+ */
+ public boolean supportsZeroLabels() { return min == 0; }
+
+ /**
+ * Whether this cardinality allows label mutation (addLabel/dropLabel).
+ */
+ public boolean supportsMutation() { return mutable; }
+}
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/io/binary/types/EdgeSerializer.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/io/binary/types/EdgeSerializer.java
index fe48d6f6ae..2f63384fcf 100644
--- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/io/binary/types/EdgeSerializer.java
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/io/binary/types/EdgeSerializer.java
@@ -100,26 +100,17 @@ public class EdgeSerializer extends SimpleTypeSerializer<Edge> {
context.write(value.id(), buffer);
// Write all edge labels as List<String> for multi-label support
final Set<String> edgeLabels = value.labels();
- if (edgeLabels == null || edgeLabels.isEmpty()) {
- throw new IOException("Unexpected null or empty labels when nullable is false");
- }
- context.writeValue(new ArrayList<>(edgeLabels), buffer, false);
+ context.writeValue(edgeLabels == null ? new ArrayList<>() : new ArrayList<>(edgeLabels), buffer, false);
context.write(value.inVertex().id(), buffer);
// Write all inVertex labels as List<String> for multi-label support
final Set<String> inVLabels = value.inVertex().labels();
- if (inVLabels == null || inVLabels.isEmpty()) {
- throw new IOException("Unexpected null or empty labels when nullable is false");
- }
- context.writeValue(new ArrayList<>(inVLabels), buffer, false);
+ context.writeValue(inVLabels == null ? new ArrayList<>() : new ArrayList<>(inVLabels), buffer, false);
context.write(value.outVertex().id(), buffer);
// Write all outVertex labels as List<String> for multi-label support
final Set<String> outVLabels = value.outVertex().labels();
- if (outVLabels == null || outVLabels.isEmpty()) {
- throw new IOException("Unexpected null or empty labels when nullable is false");
- }
- context.writeValue(new ArrayList<>(outVLabels), buffer, false);
+ context.writeValue(outVLabels == null ? new ArrayList<>() : new ArrayList<>(outVLabels), buffer, false);
// we don't serialize the parent Vertex for edges.
context.write(null, buffer);
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/io/binary/types/GraphSerializer.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/io/binary/types/GraphSerializer.java
index 4138555dc1..62f5e2546c 100644
--- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/io/binary/types/GraphSerializer.java
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/io/binary/types/GraphSerializer.java
@@ -135,7 +135,8 @@ public class GraphSerializer extends SimpleTypeSerializer<Graph> {
context.write(vertex.id(), buffer);
// serializing label as list here for now according to GraphBinaryV4
- context.writeValue(Collections.singletonList(vertex.label()), buffer, false);
+ final String vLabel = vertex.label();
+ context.writeValue(vLabel == null ? Collections.emptyList() : Collections.singletonList(vLabel), buffer, false);
context.writeValue(vertexProperties.size(), buffer, false);
for (VertexProperty<Object> vp : vertexProperties) {
@@ -154,7 +155,8 @@ public class GraphSerializer extends SimpleTypeSerializer<Graph> {
private void writeEdge(Buffer buffer, GraphBinaryWriter context, Edge edge) throws IOException {
context.write(edge.id(), buffer);
// serializing label as list here for now according to GraphBinaryV4
- context.writeValue(Collections.singletonList(edge.label()), buffer, false);
+ final String eLabel = edge.label();
+ context.writeValue(eLabel == null ? Collections.emptyList() : Collections.singletonList(eLabel), buffer, false);
context.write(edge.inVertex().id(), buffer);
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/io/binary/types/VertexSerializer.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/io/binary/types/VertexSerializer.java
index ce6befecba..f5074cc643 100644
--- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/io/binary/types/VertexSerializer.java
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/io/binary/types/VertexSerializer.java
@@ -72,11 +72,9 @@ public class VertexSerializer extends SimpleTypeSerializer<Vertex> {
protected void writeValue(final Vertex value, final Buffer buffer, final GraphBinaryWriter context) throws IOException {
context.write(value.id(), buffer);
// Write all labels as List<String> for multi-label support.
+ // Empty list is valid for zero-label elements (ZERO_OR_MORE / ZERO_OR_ONE cardinality).
final java.util.Set<String> labels = value.labels();
- if (labels == null || labels.isEmpty()) {
- throw new IOException("Unexpected null or empty labels when nullable is false");
- }
- context.writeValue(new ArrayList<>(labels), buffer, false);
+ context.writeValue(labels == null ? new ArrayList<>() : new ArrayList<>(labels), buffer, false);
if (value instanceof ReferenceVertex) {
context.write(null, buffer);
}
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/io/graphml/GraphMLWriter.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/io/graphml/GraphMLWriter.java
index cae0f9c987..0c75805f3a 100644
--- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/io/graphml/GraphMLWriter.java
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/io/graphml/GraphMLWriter.java
@@ -266,7 +266,7 @@ public final class GraphMLWriter implements GraphWriter {
writer.writeStartElement(GraphMLTokens.DATA);
writer.writeAttribute(GraphMLTokens.KEY, this.edgeLabelKey);
- writer.writeCharacters(edge.label());
+ writer.writeCharacters(edge.label() == null ? "" : edge.label());
writer.writeEndElement();
final List<String> keys = new ArrayList<>(edge.keys());
@@ -296,7 +296,7 @@ public final class GraphMLWriter implements GraphWriter {
writer.writeStartElement(GraphMLTokens.DATA);
writer.writeAttribute(GraphMLTokens.KEY, this.edgeLabelKey);
- writer.writeCharacters(edge.label());
+ writer.writeCharacters(edge.label() == null ? "" : edge.label());
writer.writeEndElement();
for (String key : edge.keys()) {
@@ -328,7 +328,7 @@ public final class GraphMLWriter implements GraphWriter {
writer.writeStartElement(GraphMLTokens.DATA);
writer.writeAttribute(GraphMLTokens.KEY, this.vertexLabelKey);
- writer.writeCharacters(vertex.label());
+ writer.writeCharacters(vertex.label() == null ? "" : vertex.label());
writer.writeEndElement();
for (String key : keys) {
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/io/graphson/GraphSONSerializersV1.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/io/graphson/GraphSONSerializersV1.java
index db4d4a8d60..feb49e9487 100644
--- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/io/graphson/GraphSONSerializersV1.java
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/io/graphson/GraphSONSerializersV1.java
@@ -139,10 +139,10 @@ final class GraphSONSerializersV1 {
if (typeSerializer != null) jsonGenerator.writeStringField(GraphSONTokens.CLASS, HashMap.class.getName());
GraphSONUtil.writeWithType(GraphSONTokens.ID, edge.id(), jsonGenerator, serializerProvider, typeSerializer);
- jsonGenerator.writeStringField(GraphSONTokens.LABEL, edge.label());
+ jsonGenerator.writeStringField(GraphSONTokens.LABEL, edge.label() == null ? "" : edge.label());
jsonGenerator.writeStringField(GraphSONTokens.TYPE, GraphSONTokens.EDGE);
- jsonGenerator.writeStringField(GraphSONTokens.IN_LABEL, edge.inVertex().label());
- jsonGenerator.writeStringField(GraphSONTokens.OUT_LABEL, edge.outVertex().label());
+ jsonGenerator.writeStringField(GraphSONTokens.IN_LABEL, edge.inVertex().label() == null ? "" : edge.inVertex().label());
+ jsonGenerator.writeStringField(GraphSONTokens.OUT_LABEL, edge.outVertex().label() == null ? "" : edge.outVertex().label());
GraphSONUtil.writeWithType(GraphSONTokens.IN, edge.inVertex().id(), jsonGenerator, serializerProvider, typeSerializer);
GraphSONUtil.writeWithType(GraphSONTokens.OUT, edge.outVertex().id(), jsonGenerator, serializerProvider, typeSerializer);
writeProperties(edge, jsonGenerator, serializerProvider, typeSerializer);
@@ -195,7 +195,7 @@ final class GraphSONSerializersV1 {
jsonGenerator.writeStartObject();
if (typeSerializer != null) jsonGenerator.writeStringField(GraphSONTokens.CLASS, HashMap.class.getName());
GraphSONUtil.writeWithType(GraphSONTokens.ID, vertex.id(), jsonGenerator, serializerProvider, typeSerializer);
- jsonGenerator.writeStringField(GraphSONTokens.LABEL, vertex.label());
+ jsonGenerator.writeStringField(GraphSONTokens.LABEL, vertex.label() == null ? "" : vertex.label());
jsonGenerator.writeStringField(GraphSONTokens.TYPE, GraphSONTokens.VERTEX);
writeProperties(vertex, jsonGenerator, serializerProvider, typeSerializer);
jsonGenerator.writeEndObject();
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/io/graphson/GraphSONSerializersV2.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/io/graphson/GraphSONSerializersV2.java
index c3113ebfe4..745d9ceb90 100644
--- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/io/graphson/GraphSONSerializersV2.java
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/io/graphson/GraphSONSerializersV2.java
@@ -100,7 +100,7 @@ class GraphSONSerializersV2 {
jsonGenerator.writeStartObject();
jsonGenerator.writeObjectField(GraphSONTokens.ID, vertex.id());
- jsonGenerator.writeStringField(GraphSONTokens.LABEL, vertex.label());
+ jsonGenerator.writeStringField(GraphSONTokens.LABEL, vertex.label() == null ? "" : vertex.label());
writeProperties(vertex, jsonGenerator);
jsonGenerator.writeEndObject();
@@ -149,9 +149,9 @@ class GraphSONSerializersV2 {
jsonGenerator.writeStartObject();
jsonGenerator.writeObjectField(GraphSONTokens.ID, edge.id());
- jsonGenerator.writeStringField(GraphSONTokens.LABEL, edge.label());
- jsonGenerator.writeStringField(GraphSONTokens.IN_LABEL, edge.inVertex().label());
- jsonGenerator.writeStringField(GraphSONTokens.OUT_LABEL, edge.outVertex().label());
+ jsonGenerator.writeStringField(GraphSONTokens.LABEL, edge.label() == null ? "" : edge.label());
+ jsonGenerator.writeStringField(GraphSONTokens.IN_LABEL, edge.inVertex().label() == null ? "" : edge.inVertex().label());
+ jsonGenerator.writeStringField(GraphSONTokens.OUT_LABEL, edge.outVertex().label() == null ? "" : edge.outVertex().label());
jsonGenerator.writeObjectField(GraphSONTokens.IN, edge.inVertex().id());
jsonGenerator.writeObjectField(GraphSONTokens.OUT, edge.outVertex().id());
writeProperties(edge, jsonGenerator);
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/io/graphson/GraphSONSerializersV3.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/io/graphson/GraphSONSerializersV3.java
index b6761dc529..650d8e599f 100644
--- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/io/graphson/GraphSONSerializersV3.java
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/io/graphson/GraphSONSerializersV3.java
@@ -101,7 +101,7 @@ class GraphSONSerializersV3 {
jsonGenerator.writeStartObject();
jsonGenerator.writeObjectField(GraphSONTokens.ID, vertex.id());
- jsonGenerator.writeStringField(GraphSONTokens.LABEL, vertex.label());
+ jsonGenerator.writeStringField(GraphSONTokens.LABEL, vertex.label() == null ? "" : vertex.label());
writeTypeForGraphObjectIfUntyped(jsonGenerator, typeInfo, GraphSONTokens.VERTEX);
writeProperties(vertex, jsonGenerator, serializerProvider);
@@ -161,10 +161,10 @@ class GraphSONSerializersV3 {
jsonGenerator.writeStartObject();
jsonGenerator.writeObjectField(GraphSONTokens.ID, edge.id());
- jsonGenerator.writeStringField(GraphSONTokens.LABEL, edge.label());
+ jsonGenerator.writeStringField(GraphSONTokens.LABEL, edge.label() == null ? "" : edge.label());
writeTypeForGraphObjectIfUntyped(jsonGenerator, typeInfo, GraphSONTokens.EDGE);
- jsonGenerator.writeStringField(GraphSONTokens.IN_LABEL, edge.inVertex().label());
- jsonGenerator.writeStringField(GraphSONTokens.OUT_LABEL, edge.outVertex().label());
+ jsonGenerator.writeStringField(GraphSONTokens.IN_LABEL, edge.inVertex().label() == null ? "" : edge.inVertex().label());
+ jsonGenerator.writeStringField(GraphSONTokens.OUT_LABEL, edge.outVertex().label() == null ? "" : edge.outVertex().label());
jsonGenerator.writeObjectField(GraphSONTokens.IN, edge.inVertex().id());
jsonGenerator.writeObjectField(GraphSONTokens.OUT, edge.outVertex().id());
writeProperties(edge, jsonGenerator);
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/io/gryo/GryoSerializersV3.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/io/gryo/GryoSerializersV3.java
index 0b748813f5..a54239972d 100644
--- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/io/gryo/GryoSerializersV3.java
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/io/gryo/GryoSerializersV3.java
@@ -75,7 +75,7 @@ public final class GryoSerializersV3 {
@Override
public <O extends OutputShim> void write(final KryoShim<?, O> kryo, final O output, final Edge edge) {
kryo.writeClassAndObject(output, edge.id());
- output.writeString(edge.label());
+ output.writeString(edge.label() == null ? "" : edge.label());
kryo.writeClassAndObject(output, edge.inVertex().id());
// temporary try/catch perhaps? need this to get SparkSingleIterationStrategyTest to work. Trying to grab
@@ -85,7 +85,8 @@ public final class GryoSerializersV3 {
//
// ghetto
try {
- output.writeString(edge.inVertex().label());
+ final String inLabel = edge.inVertex().label();
+ output.writeString(inLabel == null ? Vertex.DEFAULT_LABEL : inLabel);
} catch (Exception ex) {
output.writeString(Vertex.DEFAULT_LABEL);
}
@@ -94,7 +95,8 @@ public final class GryoSerializersV3 {
// same nonsense as above for a default label
try {
- output.writeString(edge.outVertex().label());
+ final String outLabel = edge.outVertex().label();
+ output.writeString(outLabel == null ? Vertex.DEFAULT_LABEL : outLabel);
} catch (Exception ex) {
output.writeString(Vertex.DEFAULT_LABEL);
}
@@ -133,7 +135,7 @@ public final class GryoSerializersV3 {
@Override
public <O extends OutputShim> void write(final KryoShim<?, O> kryo, final O output, final Vertex vertex) {
kryo.writeClassAndObject(output, vertex.id());
- output.writeString(vertex.label());
+ output.writeString(vertex.label() == null ? "" : vertex.label());
final Iterator<? extends VertexProperty> properties = vertex.properties();
output.writeBoolean(properties.hasNext());
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/util/LabelCardinalityValidator.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/util/LabelCardinalityValidator.java
new file mode 100644
index 0000000000..82f1c2c863
--- /dev/null
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/util/LabelCardinalityValidator.java
@@ -0,0 +1,104 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tinkerpop.gremlin.structure.util;
+
+import org.apache.tinkerpop.gremlin.structure.LabelCardinality;
+
+import java.util.HashSet;
+import java.util.Set;
+
+/**
+ * Validates label operations against a {@link LabelCardinality} constraint. All methods are stateless and static.
+ * <p>
+ * This class is separated from the enum so that cardinality remains a pure data descriptor while validation
+ * logic can be extended, overridden by providers, or tested independently.
+ *
+ * @since 4.0.0
+ */
+public final class LabelCardinalityValidator {
+
+ private LabelCardinalityValidator() {}
+
+ /**
+ * Validates that adding labels would not violate cardinality constraints.
+ *
+ * @throws IllegalStateException if mutation is not supported or max would be exceeded
+ */
+ public static void validateAdd(final LabelCardinality cardinality, final Set<String> currentLabels,
+ final String label, final String... moreLabels) {
+ if (!cardinality.supportsMutation())
+ throw new IllegalStateException("Label mutation is not supported with cardinality " + cardinality +
+ ". Labels are immutable once assigned.");
+ if (currentLabels.size() + 1 + moreLabels.length > cardinality.max())
+ throw new IllegalStateException("Cannot add label(s): would result in " +
+ (currentLabels.size() + 1 + moreLabels.length) + " labels but cardinality " +
+ cardinality + " allows at most " + cardinality.max() + ".");
+ }
+
+ /**
+ * Validates that dropping specific labels would not violate cardinality constraints.
+ * Simulates the removal to check whether the minimum label count would be violated.
+ *
+ * @throws IllegalStateException if mutation is not supported or min would be violated
+ */
+ public static void validateDrop(final LabelCardinality cardinality, final Set<String> currentLabels,
+ final String label, final String... moreLabels) {
+ if (!cardinality.supportsMutation())
+ throw new IllegalStateException("Label mutation is not supported with cardinality " + cardinality +
+ ". Labels are immutable once assigned.");
+ if (cardinality.min() > 0) {
+ final Set<String> result = new HashSet<>(currentLabels);
+ result.remove(label);
+ for (final String l : moreLabels) {
+ result.remove(l);
+ }
+ if (result.size() < cardinality.min())
+ throw new IllegalStateException("Cannot drop label(s): would leave " + result.size() +
+ " labels but cardinality " + cardinality + " requires at least " + cardinality.min() + ".");
+ }
+ }
+
+ /**
+ * Validates that dropping all labels would not violate cardinality constraints.
+ *
+ * @throws IllegalStateException if mutation is not supported or min > 0
+ */
+ public static void validateDropAll(final LabelCardinality cardinality, final Set<String> currentLabels) {
+ if (!cardinality.supportsMutation())
+ throw new IllegalStateException("Label mutation is not supported with cardinality " + cardinality +
+ ". Labels are immutable once assigned.");
+ if (cardinality.min() > 0)
+ throw new IllegalStateException("Cannot drop all labels: cardinality " + cardinality +
+ " requires at least " + cardinality.min() + " label(s).");
+ }
+
+ /**
+ * Validates that a set of labels is valid for element creation under this cardinality.
+ *
+ * @throws IllegalStateException if the label count violates min or max
+ */
+ public static void validateCreation(final LabelCardinality cardinality, final Set<String> labels) {
+ if (labels.size() < cardinality.min())
+ throw new IllegalStateException("Element creation requires at least " + cardinality.min() +
+ " label(s) with cardinality " + cardinality + ", got " + labels.size());
+ if (labels.size() > cardinality.max())
+ throw new IllegalStateException("Element creation allows at most " + cardinality.max() +
+ " label(s) with cardinality " + cardinality + ", got " + labels.size());
+ }
+}
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/util/star/StarGraph.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/util/star/StarGraph.java
index 1981a3257b..30c5cb9066 100644
--- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/util/star/StarGraph.java
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/util/star/StarGraph.java
@@ -205,7 +205,13 @@ public final class StarGraph implements Graph, Serializable {
if (vertex instanceof StarVertex) return (StarGraph) vertex.graph();
// else convert to a star graph
final StarGraph starGraph = new StarGraph();
- final StarVertex starVertex = (StarVertex) starGraph.addVertex(T.id, vertex.id(), T.label, vertex.label());
+ final String vertexLabel = vertex.label();
+ final StarVertex starVertex;
+ if (vertexLabel != null) {
+ starVertex = (StarVertex) starGraph.addVertex(T.id, vertex.id(), T.label, vertexLabel);
+ } else {
+ starVertex = (StarVertex) starGraph.addVertex(T.id, vertex.id());
+ }
// Copy multi-labels from source vertex
final Set<String> srcLabels = vertex.labels();
@@ -221,7 +227,8 @@ public final class StarGraph implements Graph, Serializable {
vp.properties().forEachRemaining(p -> starVertexProperty.property(p.key(), p.value()));
});
vertex.edges(Direction.IN).forEachRemaining(edge -> {
- final Edge starEdge = starVertex.addInEdge(edge.label(), starGraph.addVertex(T.id, edge.outVertex().id()), T.id, edge.id());
+ final String edgeLabel = edge.label() == null ? Edge.DEFAULT_LABEL : edge.label();
+ final Edge starEdge = starVertex.addInEdge(edgeLabel, starGraph.addVertex(T.id, edge.outVertex().id()), T.id, edge.id());
edge.properties().forEachRemaining(p -> starEdge.property(p.key(), p.value()));
final Set<String> edgeSrcLabels = edge.labels();
if (edgeSrcLabels.size() > 1) {
@@ -230,7 +237,8 @@ public final class StarGraph implements Graph, Serializable {
});
vertex.edges(Direction.OUT).forEachRemaining(edge -> {
- final Edge starEdge = starVertex.addOutEdge(edge.label(), starGraph.addVertex(T.id, edge.inVertex().id()), T.id, edge.id());
+ final String edgeLabel = edge.label() == null ? Edge.DEFAULT_LABEL : edge.label();
+ final Edge starEdge = starVertex.addOutEdge(edgeLabel, starGraph.addVertex(T.id, edge.inVertex().id()), T.id, edge.id());
edge.properties().forEachRemaining(p -> starEdge.property(p.key(), p.value()));
final Set<String> edgeSrcLabels = edge.labels();
if (edgeSrcLabels.size() > 1) {
diff --git a/gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Gherkin/Gremlin.cs b/gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Gherkin/Gremlin.cs
index 5728b738ba..1b876c1baa 100644
--- a/gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Gherkin/Gremlin.cs
+++ b/gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Gherkin/Gremlin.cs
@@ -1253,6 +1253,7 @@ namespace Gremlin.Net.IntegrationTest.Gherkin
{"g_V_valuesXnameX_lTrim", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.AddV((string) "person").Property("name", " marko ").Property("age", 29).As("marko").AddV((string) "person").Property("name", " vadas ").Property("age", 27).As("vadas").AddV((string) "software").Property("name", " lop").Property("lang", "java").As("lop").AddV((string) "person").Property("name", "josh ").Property("age", 32).As("josh").AddV((string) "softwar [...]
{"g_V_valuesXnameX_order_fold_lTrimXlocalX", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.AddV((string) "person").Property("name", " marko ").Property("age", 29).As("marko").AddV((string) "person").Property("name", " vadas ").Property("age", 27).As("vadas").AddV((string) "software").Property("name", " lop").Property("lang", "java").As("lop").AddV((string) "person").Property("name", "josh ").Property("age", 32).As("josh").AddV [...]
{"g_V_hasLabelXpersonX_labels", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.V().HasLabel("person").Labels()}},
+ {"g_addVXa_bX_labels_fold", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.AddV((string) "a", (string) "b"), (g,p) =>g.V().Labels().Fold()}},
{"g_addVXa_bX_labels_count", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.AddV((string) "a", (string) "b"), (g,p) =>g.V().Labels().Count()}},
{"g_addV_labels", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.AddV(), (g,p) =>g.V().Labels()}},
{"g_E_labels", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.E().HasLabel("knows").Labels()}},
@@ -1524,13 +1525,12 @@ namespace Gremlin.Net.IntegrationTest.Gherkin
{"g_injectXlist1_list2_list3X_fold_asXmX_mergeVXselectXmX_limitXlocal_1X_unfoldX_optionXonCreate_selectXmX_rangeXlocal_1_2X_unfoldX_optionXonMatch_selectXmX_tailXlocalX_unfoldX_to_create", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.AddV((string) "person").Property("name", "marko").Property("age", 29), (g,p) =>g.Inject<object>(new Dictionary<object, object> {{ T.Label, "person" }, { "name", "stephen" }}, new Dictionary<object, o [...]
{"g_mergeVXlabel_ab_name_markoX_multilabel_create", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.MergeV((IDictionary<object, object>) new Dictionary<object, object> {{ T.Label, new List<object> { "person", "employee" } }, { "name", "marko" }}), (g,p) =>g.V(), (g,p) =>g.V().HasLabel("person").HasLabel("employee"), (g,p) =>g.V().Has("name", "marko")}},
{"g_mergeVXlabel_abc_name_testX_multilabel_create", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.MergeV((IDictionary<object, object>) new Dictionary<object, object> {{ T.Label, new List<object> { "a", "b", "c" } }, { "name", "test" }}), (g,p) =>g.V(), (g,p) =>g.V().HasLabel("a").HasLabel("b").HasLabel("c")}},
+ {"g_mergeVXlabel_person_name_markoX_single_label", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.MergeV((IDictionary<object, object>) new Dictionary<object, object> {{ T.Label, "person" }, { "name", "marko" }}), (g,p) =>g.V(), (g,p) =>g.V().HasLabel("person"), (g,p) =>g.V().Has("name", "marko")}},
{"g_mergeVXlabel_ab_name_markoX_multilabel_match", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.AddV((string) "person").AddLabel("employee").Property("name", "marko"), (g,p) =>g.MergeV((IDictionary<object, object>) new Dictionary<object, object> {{ T.Label, new List<object> { "person", "employee" } }, { "name", "marko" }}), (g,p) =>g.V(), (g,p) =>g.V().HasLabel("person").HasLabel("employee")}},
{"g_mergeVXlabel_ab_name_markoX_multilabel_nomatch", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.AddV((string) "person").Property("name", "marko"), (g,p) =>g.MergeV((IDictionary<object, object>) new Dictionary<object, object> {{ T.Label, new List<object> { "person", "employee" } }, { "name", "marko" }}), (g,p) =>g.V()}},
{"g_mergeVXlabel_person_name_markoX_optionXonMatch_label_managerX", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.AddV((string) "person").AddLabel("employee").Property("name", "marko"), (g,p) =>g.MergeV((IDictionary<object, object>) new Dictionary<object, object> {{ T.Label, "person" }, { "name", "marko" }}).Option(Merge.OnMatch, (IDictionary<object, object>) new Dictionary<object, object> {{ T.Label, "manager" }}), (g,p) =>g.V(), [...]
{"g_mergeVXlabel_person_name_markoX_optionXonMatch_label_manager_directorX", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.AddV((string) "person").Property("name", "marko"), (g,p) =>g.MergeV((IDictionary<object, object>) new Dictionary<object, object> {{ T.Label, "person" }, { "name", "marko" }}).Option(Merge.OnMatch, (IDictionary<object, object>) new Dictionary<object, object> {{ T.Label, new List<object> { "manager", "director" [...]
{"g_mergeVXlabel_person_name_markoX_optionXonMatch_label_emptyX", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.AddV((string) "person").Property("name", "marko"), (g,p) =>g.MergeV((IDictionary<object, object>) new Dictionary<object, object> {{ T.Label, "person" }, { "name", "marko" }}).Option(Merge.OnMatch, (IDictionary<object, object>) new Dictionary<object, object> {{ T.Label, new List<object> { } }}), (g,p) =>g.V(), (g,p) =>g. [...]
- {"g_mergeVXname_markoX_optionXonCreate_label_ab_name_markoX", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.MergeV((IDictionary<object, object>) new Dictionary<object, object> {{ "name", "marko" }}).Option(Merge.OnCreate, (IDictionary<object, object>) new Dictionary<object, object> {{ T.Label, new List<object> { "person", "employee" } }, { "name", "marko" }}), (g,p) =>g.V(), (g,p) =>g.V().HasLabel("person").HasLabel("employee"), ( [...]
- {"g_mergeVXlabel_person_name_markoX_optionXonMatch_label_existingX", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.AddV((string) "person").AddLabel("employee").Property("name", "marko"), (g,p) =>g.MergeV((IDictionary<object, object>) new Dictionary<object, object> {{ T.Label, "person" }, { "name", "marko" }}).Option(Merge.OnMatch, (IDictionary<object, object>) new Dictionary<object, object> {{ T.Label, "person" }}), (g,p) =>g.V(), [...]
{"g_V_age_min", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.V().Values<object>("age").Min<object>()}},
{"g_V_foo_min", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.V().Values<object>("foo").Min<object>()}},
{"g_V_name_min", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.V().Values<object>("name").Min<object>()}},
@@ -2083,7 +2083,6 @@ namespace Gremlin.Net.IntegrationTest.Gherkin
{"g_V_dropLabels_defaultLabel", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.AddV((string) "person"), (g,p) =>g.V().DropLabels().Labels()}},
{"g_E_dropLabelXknowsX_labels", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.AddV((string) "person").As("a").AddV((string) "person").As("b").AddE((string) "knows").From("a").To("b"), (g,p) =>g.E().DropLabel("knows").Labels().Fold()}},
{"g_E_dropLabels_labels", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.AddV((string) "person").As("a").AddV((string) "person").As("b").AddE((string) "knows").From("a").To("b"), (g,p) =>g.E().DropLabels().Labels()}},
- {"g_V_dropLabelXnonExistentX_labels", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.AddV((string) "a", (string) "b"), (g,p) =>g.V().DropLabel("xyz").Labels()}},
{"g_V_fail", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.V().Fail()}},
{"g_V_failXmsgX", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.V().Fail("msg")}},
{"g_V_unionXout_failX", new List<Func<GraphTraversalSource, IDictionary<string, object>, ITraversal>> {(g,p) =>g.V().Union<object>(__.Out(), __.Fail())}},
diff --git a/gremlin-go/driver/cucumber/gremlin.go b/gremlin-go/driver/cucumber/gremlin.go
index a688116d6f..14ca83bc81 100644
--- a/gremlin-go/driver/cucumber/gremlin.go
+++ b/gremlin-go/driver/cucumber/gremlin.go
@@ -1223,6 +1223,7 @@ var translationMap = map[string][]func(g *gremlingo.GraphTraversalSource, p map[
"g_V_valuesXnameX_lTrim": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.AddV("person").Property("name", " marko ").Property("age", 29).As("marko").AddV("person").Property("name", " vadas ").Property("age", 27).As("vadas").AddV("software").Property("name", " lop").Property("lang", "java").As("lop").AddV("person").Property("name", "josh ").Property("age", 32).As("josh").AddV("software").Property("name", " ripple ").Proper [...]
"g_V_valuesXnameX_order_fold_lTrimXlocalX": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.AddV("person").Property("name", " marko ").Property("age", 29).As("marko").AddV("person").Property("name", " vadas ").Property("age", 27).As("vadas").AddV("software").Property("name", " lop").Property("lang", "java").As("lop").AddV("person").Property("name", "josh ").Property("age", 32).As("josh").AddV("software").Property("name", " [...]
"g_V_hasLabelXpersonX_labels": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.V().HasLabel("person").Labels()}},
+ "g_addVXa_bX_labels_fold": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.AddV("a", "b")}, func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.V().Labels().Fold()}},
"g_addVXa_bX_labels_count": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.AddV("a", "b")}, func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.V().Labels().Count()}},
"g_addV_labels": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.AddV()}, func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.V().Labels()}},
"g_E_labels": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.E().HasLabel("knows").Labels()}},
@@ -1494,13 +1495,12 @@ var translationMap = map[string][]func(g *gremlingo.GraphTraversalSource, p map[
"g_injectXlist1_list2_list3X_fold_asXmX_mergeVXselectXmX_limitXlocal_1X_unfoldX_optionXonCreate_selectXmX_rangeXlocal_1_2X_unfoldX_optionXonMatch_selectXmX_tailXlocalX_unfoldX_to_create": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.AddV("person").Property("name", "marko").Property("age", 29)}, func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.Inject(map[interface{}]interface [...]
"g_mergeVXlabel_ab_name_markoX_multilabel_create": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.MergeV(map[interface{}]interface{}{gremlingo.T.Label: []interface{}{"person", "employee"}, "name": "marko" })}, func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.V()}, func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.V().HasLabel [...]
"g_mergeVXlabel_abc_name_testX_multilabel_create": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.MergeV(map[interface{}]interface{}{gremlingo.T.Label: []interface{}{"a", "b", "c"}, "name": "test" })}, func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.V()}, func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.V().HasLabel("a").Ha [...]
+ "g_mergeVXlabel_person_name_markoX_single_label": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.MergeV(map[interface{}]interface{}{gremlingo.T.Label: "person", "name": "marko" })}, func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.V()}, func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.V().HasLabel("person")}, func(g *gremlin [...]
"g_mergeVXlabel_ab_name_markoX_multilabel_match": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.AddV("person").AddLabel("employee").Property("name", "marko")}, func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.MergeV(map[interface{}]interface{}{gremlingo.T.Label: []interface{}{"person", "employee"}, "name": "marko" })}, func(g *gremlingo.GraphTraversalSource, p map[string]inte [...]
"g_mergeVXlabel_ab_name_markoX_multilabel_nomatch": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.AddV("person").Property("name", "marko")}, func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.MergeV(map[interface{}]interface{}{gremlingo.T.Label: []interface{}{"person", "employee"}, "name": "marko" })}, func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo [...]
"g_mergeVXlabel_person_name_markoX_optionXonMatch_label_managerX": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.AddV("person").AddLabel("employee").Property("name", "marko")}, func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.MergeV(map[interface{}]interface{}{gremlingo.T.Label: "person", "name": "marko" }).Option(gremlingo.Merge.OnMatch, map[interface{}]interface{}{gremlingo [...]
"g_mergeVXlabel_person_name_markoX_optionXonMatch_label_manager_directorX": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.AddV("person").Property("name", "marko")}, func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.MergeV(map[interface{}]interface{}{gremlingo.T.Label: "person", "name": "marko" }).Option(gremlingo.Merge.OnMatch, map[interface{}]interface{}{gremlingo.T.Label: [] [...]
"g_mergeVXlabel_person_name_markoX_optionXonMatch_label_emptyX": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.AddV("person").Property("name", "marko")}, func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.MergeV(map[interface{}]interface{}{gremlingo.T.Label: "person", "name": "marko" }).Option(gremlingo.Merge.OnMatch, map[interface{}]interface{}{gremlingo.T.Label: []interface{} [...]
- "g_mergeVXname_markoX_optionXonCreate_label_ab_name_markoX": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.MergeV(map[interface{}]interface{}{"name": "marko" }).Option(gremlingo.Merge.OnCreate, map[interface{}]interface{}{gremlingo.T.Label: []interface{}{"person", "employee"}, "name": "marko" })}, func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.V()}, func(g *gremlingo.GraphT [...]
- "g_mergeVXlabel_person_name_markoX_optionXonMatch_label_existingX": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.AddV("person").AddLabel("employee").Property("name", "marko")}, func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.MergeV(map[interface{}]interface{}{gremlingo.T.Label: "person", "name": "marko" }).Option(gremlingo.Merge.OnMatch, map[interface{}]interface{}{gremling [...]
"g_V_age_min": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.V().Values("age").Min()}},
"g_V_foo_min": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.V().Values("foo").Min()}},
"g_V_name_min": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.V().Values("name").Min()}},
@@ -2053,7 +2053,6 @@ var translationMap = map[string][]func(g *gremlingo.GraphTraversalSource, p map[
"g_V_dropLabels_defaultLabel": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.AddV("person")}, func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.V().DropLabels().Labels()}},
"g_E_dropLabelXknowsX_labels": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.AddV("person").As("a").AddV("person").As("b").AddE("knows").From("a").To("b")}, func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.E().DropLabel("knows").Labels().Fold()}},
"g_E_dropLabels_labels": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.AddV("person").As("a").AddV("person").As("b").AddE("knows").From("a").To("b")}, func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.E().DropLabels().Labels()}},
- "g_V_dropLabelXnonExistentX_labels": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.AddV("a", "b")}, func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.V().DropLabel("xyz").Labels()}},
"g_V_fail": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.V().Fail()}},
"g_V_failXmsgX": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.V().Fail("msg")}},
"g_V_unionXout_failX": {func(g *gremlingo.GraphTraversalSource, p map[string]interface{}) *gremlingo.GraphTraversal {return g.V().Union(gremlingo.T__.Out(), gremlingo.T__.Fail())}},
diff --git a/gremlin-js/gremlin-javascript/test/cucumber/gremlin.js b/gremlin-js/gremlin-javascript/test/cucumber/gremlin.js
index 97df92ce24..fed99737ac 100644
--- a/gremlin-js/gremlin-javascript/test/cucumber/gremlin.js
+++ b/gremlin-js/gremlin-javascript/test/cucumber/gremlin.js
@@ -1254,6 +1254,7 @@ const gremlins = {
g_V_valuesXnameX_lTrim: [function({g}) { return g.addV("person").property("name", " marko ").property("age", 29).as("marko").addV("person").property("name", " vadas ").property("age", 27).as("vadas").addV("software").property("name", " lop").property("lang", "java").as("lop").addV("person").property("name", "josh ").property("age", 32).as("josh").addV("software").property("name", " ripple ").property("lang", "java").as("ripple").addV("person").property("name", "peter").proper [...]
g_V_valuesXnameX_order_fold_lTrimXlocalX: [function({g}) { return g.addV("person").property("name", " marko ").property("age", 29).as("marko").addV("person").property("name", " vadas ").property("age", 27).as("vadas").addV("software").property("name", " lop").property("lang", "java").as("lop").addV("person").property("name", "josh ").property("age", 32).as("josh").addV("software").property("name", " ripple ").property("lang", "java").as("ripple").addV("person").property("name [...]
g_V_hasLabelXpersonX_labels: [function({g}) { return g.V().hasLabel("person").labels() }],
+ g_addVXa_bX_labels_fold: [function({g}) { return g.addV("a", "b") }, function({g}) { return g.V().labels().fold() }],
g_addVXa_bX_labels_count: [function({g}) { return g.addV("a", "b") }, function({g}) { return g.V().labels().count() }],
g_addV_labels: [function({g}) { return g.addV() }, function({g}) { return g.V().labels() }],
g_E_labels: [function({g}) { return g.E().hasLabel("knows").labels() }],
@@ -1525,13 +1526,12 @@ const gremlins = {
g_injectXlist1_list2_list3X_fold_asXmX_mergeVXselectXmX_limitXlocal_1X_unfoldX_optionXonCreate_selectXmX_rangeXlocal_1_2X_unfoldX_optionXonMatch_selectXmX_tailXlocalX_unfoldX_to_create: [function({g}) { return g.addV("person").property("name", "marko").property("age", 29) }, function({g}) { return g.inject(new Map([[T.label, "person"], ["name", "stephen"]]), new Map([[T.label, "person"], ["name", "stephen"]]), new Map([["created", "N"]])).fold().as("m").mergeV(__.select("m").limit(Sc [...]
g_mergeVXlabel_ab_name_markoX_multilabel_create: [function({g}) { return g.mergeV(new Map([[T.label, ["person", "employee"]], ["name", "marko"]])) }, function({g}) { return g.V() }, function({g}) { return g.V().hasLabel("person").hasLabel("employee") }, function({g}) { return g.V().has("name", "marko") }],
g_mergeVXlabel_abc_name_testX_multilabel_create: [function({g}) { return g.mergeV(new Map([[T.label, ["a", "b", "c"]], ["name", "test"]])) }, function({g}) { return g.V() }, function({g}) { return g.V().hasLabel("a").hasLabel("b").hasLabel("c") }],
+ g_mergeVXlabel_person_name_markoX_single_label: [function({g}) { return g.mergeV(new Map([[T.label, "person"], ["name", "marko"]])) }, function({g}) { return g.V() }, function({g}) { return g.V().hasLabel("person") }, function({g}) { return g.V().has("name", "marko") }],
g_mergeVXlabel_ab_name_markoX_multilabel_match: [function({g}) { return g.addV("person").addLabel("employee").property("name", "marko") }, function({g}) { return g.mergeV(new Map([[T.label, ["person", "employee"]], ["name", "marko"]])) }, function({g}) { return g.V() }, function({g}) { return g.V().hasLabel("person").hasLabel("employee") }],
g_mergeVXlabel_ab_name_markoX_multilabel_nomatch: [function({g}) { return g.addV("person").property("name", "marko") }, function({g}) { return g.mergeV(new Map([[T.label, ["person", "employee"]], ["name", "marko"]])) }, function({g}) { return g.V() }],
g_mergeVXlabel_person_name_markoX_optionXonMatch_label_managerX: [function({g}) { return g.addV("person").addLabel("employee").property("name", "marko") }, function({g}) { return g.mergeV(new Map([[T.label, "person"], ["name", "marko"]])).option(Merge.onMatch, new Map([[T.label, "manager"]])) }, function({g}) { return g.V() }, function({g}) { return g.V().hasLabel("manager") }, function({g}) { return g.V().hasLabel("person") }, function({g}) { return g.V().hasLabel("employee") }],
g_mergeVXlabel_person_name_markoX_optionXonMatch_label_manager_directorX: [function({g}) { return g.addV("person").property("name", "marko") }, function({g}) { return g.mergeV(new Map([[T.label, "person"], ["name", "marko"]])).option(Merge.onMatch, new Map([[T.label, ["manager", "director"]]])) }, function({g}) { return g.V() }, function({g}) { return g.V().hasLabel("manager").hasLabel("director") }, function({g}) { return g.V().hasLabel("person") }],
g_mergeVXlabel_person_name_markoX_optionXonMatch_label_emptyX: [function({g}) { return g.addV("person").property("name", "marko") }, function({g}) { return g.mergeV(new Map([[T.label, "person"], ["name", "marko"]])).option(Merge.onMatch, new Map([[T.label, []]])) }, function({g}) { return g.V() }, function({g}) { return g.V().hasLabel("person") }],
- g_mergeVXname_markoX_optionXonCreate_label_ab_name_markoX: [function({g}) { return g.mergeV(new Map([["name", "marko"]])).option(Merge.onCreate, new Map([[T.label, ["person", "employee"]], ["name", "marko"]])) }, function({g}) { return g.V() }, function({g}) { return g.V().hasLabel("person").hasLabel("employee") }, function({g}) { return g.V().has("name", "marko") }],
- g_mergeVXlabel_person_name_markoX_optionXonMatch_label_existingX: [function({g}) { return g.addV("person").addLabel("employee").property("name", "marko") }, function({g}) { return g.mergeV(new Map([[T.label, "person"], ["name", "marko"]])).option(Merge.onMatch, new Map([[T.label, "person"]])) }, function({g}) { return g.V() }, function({g}) { return g.V().hasLabel("person").hasLabel("employee") }],
g_V_age_min: [function({g}) { return g.V().values("age").min() }],
g_V_foo_min: [function({g}) { return g.V().values("foo").min() }],
g_V_name_min: [function({g}) { return g.V().values("name").min() }],
@@ -2084,7 +2084,6 @@ const gremlins = {
g_V_dropLabels_defaultLabel: [function({g}) { return g.addV("person") }, function({g}) { return g.V().dropLabels().labels() }],
g_E_dropLabelXknowsX_labels: [function({g}) { return g.addV("person").as("a").addV("person").as("b").addE("knows").from_("a").to("b") }, function({g}) { return g.E().dropLabel("knows").labels().fold() }],
g_E_dropLabels_labels: [function({g}) { return g.addV("person").as("a").addV("person").as("b").addE("knows").from_("a").to("b") }, function({g}) { return g.E().dropLabels().labels() }],
- g_V_dropLabelXnonExistentX_labels: [function({g}) { return g.addV("a", "b") }, function({g}) { return g.V().dropLabel("xyz").labels() }],
g_V_fail: [function({g}) { return g.V().fail() }],
g_V_failXmsgX: [function({g}) { return g.V().fail("msg") }],
g_V_unionXout_failX: [function({g}) { return g.V().union(__.out(), __.fail()) }],
diff --git a/gremlin-language/src/main/antlr4/Gremlin.g4 b/gremlin-language/src/main/antlr4/Gremlin.g4
index 3392483b08..b28caae9c9 100644
--- a/gremlin-language/src/main/antlr4/Gremlin.g4
+++ b/gremlin-language/src/main/antlr4/Gremlin.g4
@@ -114,7 +114,6 @@ traversalSourceSpawnMethod
traversalSourceSpawnMethod_addE
: K_ADDE LPAREN RPAREN
| K_ADDE LPAREN stringArgument RPAREN
- | K_ADDE LPAREN stringArgument COMMA stringArgument (COMMA stringArgument)* RPAREN
| K_ADDE LPAREN nestedTraversal RPAREN
;
@@ -335,7 +334,6 @@ traversalMethod_E
traversalMethod_addE
: K_ADDE LPAREN RPAREN #traversalMethod_addE_Empty
| K_ADDE LPAREN stringArgument RPAREN #traversalMethod_addE_String
- | K_ADDE LPAREN stringArgument (COMMA stringArgument)+ RPAREN #traversalMethod_addE_StringVarargs
| K_ADDE LPAREN nestedTraversal RPAREN #traversalMethod_addE_Traversal
;
diff --git a/gremlin-python/src/main/python/tests/feature/gremlin.py b/gremlin-python/src/main/python/tests/feature/gremlin.py
index ba27449594..5c7cbe05be 100644
--- a/gremlin-python/src/main/python/tests/feature/gremlin.py
+++ b/gremlin-python/src/main/python/tests/feature/gremlin.py
@@ -1228,6 +1228,7 @@ world.gremlins = {
'g_V_valuesXnameX_lTrim': [(lambda g:g.add_v('person').property('name', ' marko ').property('age', 29).as_('marko').add_v('person').property('name', ' vadas ').property('age', 27).as_('vadas').add_v('software').property('name', ' lop').property('lang', 'java').as_('lop').add_v('person').property('name', 'josh ').property('age', 32).as_('josh').add_v('software').property('name', ' ripple ').property('lang', 'java').as_('ripple').add_v('person').property('name', 'peter').proper [...]
'g_V_valuesXnameX_order_fold_lTrimXlocalX': [(lambda g:g.add_v('person').property('name', ' marko ').property('age', 29).as_('marko').add_v('person').property('name', ' vadas ').property('age', 27).as_('vadas').add_v('software').property('name', ' lop').property('lang', 'java').as_('lop').add_v('person').property('name', 'josh ').property('age', 32).as_('josh').add_v('software').property('name', ' ripple ').property('lang', 'java').as_('ripple').add_v('person').property('name [...]
'g_V_hasLabelXpersonX_labels': [(lambda g:g.V().has_label('person').labels())],
+ 'g_addVXa_bX_labels_fold': [(lambda g:g.add_v('a', 'b')), (lambda g:g.V().labels().fold())],
'g_addVXa_bX_labels_count': [(lambda g:g.add_v('a', 'b')), (lambda g:g.V().labels().count())],
'g_addV_labels': [(lambda g:g.add_v()), (lambda g:g.V().labels())],
'g_E_labels': [(lambda g:g.E().has_label('knows').labels())],
@@ -1499,13 +1500,12 @@ world.gremlins = {
'g_injectXlist1_list2_list3X_fold_asXmX_mergeVXselectXmX_limitXlocal_1X_unfoldX_optionXonCreate_selectXmX_rangeXlocal_1_2X_unfoldX_optionXonMatch_selectXmX_tailXlocalX_unfoldX_to_create': [(lambda g:g.add_v('person').property('name', 'marko').property('age', 29)), (lambda g:g.inject({ T.label: 'person', 'name': 'stephen' }, { T.label: 'person', 'name': 'stephen' }, { 'created': 'N' }).fold().as_('m').merge_v(__.select('m').limit(Scope.local, 1).unfold()).option(Merge.on_create, __.se [...]
'g_mergeVXlabel_ab_name_markoX_multilabel_create': [(lambda g:g.merge_v({ T.label: ['person', 'employee'], 'name': 'marko' })), (lambda g:g.V()), (lambda g:g.V().has_label('person').has_label('employee')), (lambda g:g.V().has('name', 'marko'))],
'g_mergeVXlabel_abc_name_testX_multilabel_create': [(lambda g:g.merge_v({ T.label: ['a', 'b', 'c'], 'name': 'test' })), (lambda g:g.V()), (lambda g:g.V().has_label('a').has_label('b').has_label('c'))],
+ 'g_mergeVXlabel_person_name_markoX_single_label': [(lambda g:g.merge_v({ T.label: 'person', 'name': 'marko' })), (lambda g:g.V()), (lambda g:g.V().has_label('person')), (lambda g:g.V().has('name', 'marko'))],
'g_mergeVXlabel_ab_name_markoX_multilabel_match': [(lambda g:g.add_v('person').add_label('employee').property('name', 'marko')), (lambda g:g.merge_v({ T.label: ['person', 'employee'], 'name': 'marko' })), (lambda g:g.V()), (lambda g:g.V().has_label('person').has_label('employee'))],
'g_mergeVXlabel_ab_name_markoX_multilabel_nomatch': [(lambda g:g.add_v('person').property('name', 'marko')), (lambda g:g.merge_v({ T.label: ['person', 'employee'], 'name': 'marko' })), (lambda g:g.V())],
'g_mergeVXlabel_person_name_markoX_optionXonMatch_label_managerX': [(lambda g:g.add_v('person').add_label('employee').property('name', 'marko')), (lambda g:g.merge_v({ T.label: 'person', 'name': 'marko' }).option(Merge.on_match, { T.label: 'manager' })), (lambda g:g.V()), (lambda g:g.V().has_label('manager')), (lambda g:g.V().has_label('person')), (lambda g:g.V().has_label('employee'))],
'g_mergeVXlabel_person_name_markoX_optionXonMatch_label_manager_directorX': [(lambda g:g.add_v('person').property('name', 'marko')), (lambda g:g.merge_v({ T.label: 'person', 'name': 'marko' }).option(Merge.on_match, { T.label: ['manager', 'director'] })), (lambda g:g.V()), (lambda g:g.V().has_label('manager').has_label('director')), (lambda g:g.V().has_label('person'))],
'g_mergeVXlabel_person_name_markoX_optionXonMatch_label_emptyX': [(lambda g:g.add_v('person').property('name', 'marko')), (lambda g:g.merge_v({ T.label: 'person', 'name': 'marko' }).option(Merge.on_match, { T.label: [] })), (lambda g:g.V()), (lambda g:g.V().has_label('person'))],
- 'g_mergeVXname_markoX_optionXonCreate_label_ab_name_markoX': [(lambda g:g.merge_v({ 'name': 'marko' }).option(Merge.on_create, { T.label: ['person', 'employee'], 'name': 'marko' })), (lambda g:g.V()), (lambda g:g.V().has_label('person').has_label('employee')), (lambda g:g.V().has('name', 'marko'))],
- 'g_mergeVXlabel_person_name_markoX_optionXonMatch_label_existingX': [(lambda g:g.add_v('person').add_label('employee').property('name', 'marko')), (lambda g:g.merge_v({ T.label: 'person', 'name': 'marko' }).option(Merge.on_match, { T.label: 'person' })), (lambda g:g.V()), (lambda g:g.V().has_label('person').has_label('employee'))],
'g_V_age_min': [(lambda g:g.V().values('age').min_())],
'g_V_foo_min': [(lambda g:g.V().values('foo').min_())],
'g_V_name_min': [(lambda g:g.V().values('name').min_())],
@@ -2058,7 +2058,6 @@ world.gremlins = {
'g_V_dropLabels_defaultLabel': [(lambda g:g.add_v('person')), (lambda g:g.V().drop_labels().labels())],
'g_E_dropLabelXknowsX_labels': [(lambda g:g.add_v('person').as_('a').add_v('person').as_('b').add_e('knows').from_('a').to('b')), (lambda g:g.E().drop_label('knows').labels().fold())],
'g_E_dropLabels_labels': [(lambda g:g.add_v('person').as_('a').add_v('person').as_('b').add_e('knows').from_('a').to('b')), (lambda g:g.E().drop_labels().labels())],
- 'g_V_dropLabelXnonExistentX_labels': [(lambda g:g.add_v('a', 'b')), (lambda g:g.V().drop_label('xyz').labels())],
'g_V_fail': [(lambda g:g.V().fail())],
'g_V_failXmsgX': [(lambda g:g.V().fail('msg'))],
'g_V_unionXout_failX': [(lambda g:g.V().union(__.out(), __.fail()))],
diff --git a/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/language/translator/translations.json b/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/language/translator/translations.json
index 338c567b7a..86664517ff 100644
--- a/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/language/translator/translations.json
+++ b/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/language/translator/translations.json
@@ -17831,88 +17831,6 @@
}
]
},
- {
- "scenario": "g_addEXa_bX_from_V_to_V_labels_fold",
- "traversals": [
- {
- "original": "g.addV(\"person\").property(\"name\", \"marko\").addV(\"person\").property(\"name\", \"josh\")",
- "language": "g.addV(\"person\").property(\"name\", \"marko\").addV(\"person\").property(\"name\", \"josh\")",
- "canonical": "g.addV(\"person\").property(\"name\", \"marko\").addV(\"person\").property(\"name\", \"josh\")",
- "anonymized": "g.addV(string0).property(string1, string2).addV(string0).property(string1, string3)",
- "dotnet": "g.AddV((string) \"person\").Property(\"name\", \"marko\").AddV((string) \"person\").Property(\"name\", \"josh\")",
- "go": "g.AddV(\"person\").Property(\"name\", \"marko\").AddV(\"person\").Property(\"name\", \"josh\")",
- "groovy": "g.addV(\"person\").property(\"name\", \"marko\").addV(\"person\").property(\"name\", \"josh\")",
- "java": "g.addV(\"person\").property(\"name\", \"marko\").addV(\"person\").property(\"name\", \"josh\")",
- "javascript": "g.addV(\"person\").property(\"name\", \"marko\").addV(\"person\").property(\"name\", \"josh\")",
- "python": "g.add_v('person').property('name', 'marko').add_v('person').property('name', 'josh')"
- },
- {
- "original": "g.addE(\"knows\", \"trusts\").from(__.V().has(\"name\", \"marko\")).to(__.V().has(\"name\", \"josh\")).labels().fold()",
- "language": "g.addE(\"knows\", \"trusts\").from(__.V().has(\"name\", \"marko\")).to(__.V().has(\"name\", \"josh\")).labels().fold()",
- "canonical": "g.addE(\"knows\", \"trusts\").from(__.V().has(\"name\", \"marko\")).to(__.V().has(\"name\", \"josh\")).labels().fold()",
- "anonymized": "g.addE(string0, string1).from(__.V().has(string2, string3)).to(__.V().has(string2, string4)).labels().fold()",
- "dotnet": "g.AddE((string) \"knows\", (string) \"trusts\").From(__.V().Has(\"name\", \"marko\")).To(__.V().Has(\"name\", \"josh\")).Labels().Fold()",
- "go": "g.AddE(\"knows\", \"trusts\").From(gremlingo.T__.V().Has(\"name\", \"marko\")).To(gremlingo.T__.V().Has(\"name\", \"josh\")).Labels().Fold()",
- "groovy": "g.addE(\"knows\", \"trusts\").from(__.V().has(\"name\", \"marko\")).to(__.V().has(\"name\", \"josh\")).labels().fold()",
- "java": "g.addE(\"knows\", \"trusts\").from(__.V().has(\"name\", \"marko\")).to(__.V().has(\"name\", \"josh\")).labels().fold()",
- "javascript": "g.addE(\"knows\", \"trusts\").from_(__.V().has(\"name\", \"marko\")).to(__.V().has(\"name\", \"josh\")).labels().fold()",
- "python": "g.add_e('knows', 'trusts').from_(__.V().has('name', 'marko')).to(__.V().has('name', 'josh')).labels().fold()"
- },
- {
- "original": "g.E().hasLabel(\"knows\")",
- "language": "g.E().hasLabel(\"knows\")",
- "canonical": "g.E().hasLabel(\"knows\")",
- "anonymized": "g.E().hasLabel(string0)",
- "dotnet": "g.E().HasLabel(\"knows\")",
- "go": "g.E().HasLabel(\"knows\")",
- "groovy": "g.E().hasLabel(\"knows\")",
- "java": "g.E().hasLabel(\"knows\")",
- "javascript": "g.E().hasLabel(\"knows\")",
- "python": "g.E().has_label('knows')"
- },
- {
- "original": "g.E().hasLabel(\"trusts\")",
- "language": "g.E().hasLabel(\"trusts\")",
- "canonical": "g.E().hasLabel(\"trusts\")",
- "anonymized": "g.E().hasLabel(string0)",
- "dotnet": "g.E().HasLabel(\"trusts\")",
- "go": "g.E().HasLabel(\"trusts\")",
- "groovy": "g.E().hasLabel(\"trusts\")",
- "java": "g.E().hasLabel(\"trusts\")",
- "javascript": "g.E().hasLabel(\"trusts\")",
- "python": "g.E().has_label('trusts')"
- }
- ]
- },
- {
- "scenario": "g_addEXa_b_cX_from_V_to_V_labels_count",
- "traversals": [
- {
- "original": "g.addV(\"person\").property(\"name\", \"marko\").addV(\"person\").property(\"name\", \"josh\")",
- "language": "g.addV(\"person\").property(\"name\", \"marko\").addV(\"person\").property(\"name\", \"josh\")",
- "canonical": "g.addV(\"person\").property(\"name\", \"marko\").addV(\"person\").property(\"name\", \"josh\")",
- "anonymized": "g.addV(string0).property(string1, string2).addV(string0).property(string1, string3)",
- "dotnet": "g.AddV((string) \"person\").Property(\"name\", \"marko\").AddV((string) \"person\").Property(\"name\", \"josh\")",
- "go": "g.AddV(\"person\").Property(\"name\", \"marko\").AddV(\"person\").Property(\"name\", \"josh\")",
- "groovy": "g.addV(\"person\").property(\"name\", \"marko\").addV(\"person\").property(\"name\", \"josh\")",
- "java": "g.addV(\"person\").property(\"name\", \"marko\").addV(\"person\").property(\"name\", \"josh\")",
- "javascript": "g.addV(\"person\").property(\"name\", \"marko\").addV(\"person\").property(\"name\", \"josh\")",
- "python": "g.add_v('person').property('name', 'marko').add_v('person').property('name', 'josh')"
- },
- {
- "original": "g.addE(\"a\", \"b\", \"c\").from(__.V().has(\"name\", \"marko\")).to(__.V().has(\"name\", \"josh\")).labels().count()",
- "language": "g.addE(\"a\", \"b\", \"c\").from(__.V().has(\"name\", \"marko\")).to(__.V().has(\"name\", \"josh\")).labels().count()",
- "canonical": "g.addE(\"a\", \"b\", \"c\").from(__.V().has(\"name\", \"marko\")).to(__.V().has(\"name\", \"josh\")).labels().count()",
- "anonymized": "g.addE(string0, string1, string2).from(__.V().has(string3, string4)).to(__.V().has(string3, string5)).labels().count()",
- "dotnet": "g.AddE((string) \"a\", (string) \"b\", (string) \"c\").From(__.V().Has(\"name\", \"marko\")).To(__.V().Has(\"name\", \"josh\")).Labels().Count()",
- "go": "g.AddE(\"a\", \"b\", \"c\").From(gremlingo.T__.V().Has(\"name\", \"marko\")).To(gremlingo.T__.V().Has(\"name\", \"josh\")).Labels().Count()",
- "groovy": "g.addE(\"a\", \"b\", \"c\").from(__.V().has(\"name\", \"marko\")).to(__.V().has(\"name\", \"josh\")).labels().count()",
- "java": "g.addE(\"a\", \"b\", \"c\").from(__.V().has(\"name\", \"marko\")).to(__.V().has(\"name\", \"josh\")).labels().count()",
- "javascript": "g.addE(\"a\", \"b\", \"c\").from_(__.V().has(\"name\", \"marko\")).to(__.V().has(\"name\", \"josh\")).labels().count()",
- "python": "g.add_e('a', 'b', 'c').from_(__.V().has('name', 'marko')).to(__.V().has('name', 'josh')).labels().count()"
- }
- ]
- },
{
"scenario": "g_VX1X_addVXanimalX_propertyXage_selectXaX_byXageXX_propertyXname_puppyX",
"traversals": [
@@ -33369,18 +33287,6 @@
"javascript": "g.V()",
"python": "g.V()"
},
- {
- "original": "g.V().hasLabel(\"vertex\")",
- "language": "g.V().hasLabel(\"vertex\")",
- "canonical": "g.V().hasLabel(\"vertex\")",
- "anonymized": "g.V().hasLabel(string0)",
- "dotnet": "g.V().HasLabel(\"vertex\")",
- "go": "g.V().HasLabel(\"vertex\")",
- "groovy": "g.V().hasLabel(\"vertex\")",
- "java": "g.V().hasLabel(\"vertex\")",
- "javascript": "g.V().hasLabel(\"vertex\")",
- "python": "g.V().has_label('vertex')"
- },
{
"original": "g.V().hasLabel(\"person\")",
"language": "g.V().hasLabel(\"person\")",
@@ -42077,30 +41983,6 @@
"java": "g.E().addLabel(\"friend\").labels().fold()",
"javascript": "g.E().addLabel(\"friend\").labels().fold()",
"python": "g.E().add_label('friend').labels().fold()"
- },
- {
- "original": "g.E().hasLabel(\"knows\")",
- "language": "g.E().hasLabel(\"knows\")",
- "canonical": "g.E().hasLabel(\"knows\")",
- "anonymized": "g.E().hasLabel(string0)",
- "dotnet": "g.E().HasLabel(\"knows\")",
- "go": "g.E().HasLabel(\"knows\")",
- "groovy": "g.E().hasLabel(\"knows\")",
- "java": "g.E().hasLabel(\"knows\")",
- "javascript": "g.E().hasLabel(\"knows\")",
- "python": "g.E().has_label('knows')"
- },
- {
- "original": "g.E().hasLabel(\"friend\")",
- "language": "g.E().hasLabel(\"friend\")",
- "canonical": "g.E().hasLabel(\"friend\")",
- "anonymized": "g.E().hasLabel(string0)",
- "dotnet": "g.E().HasLabel(\"friend\")",
- "go": "g.E().HasLabel(\"friend\")",
- "groovy": "g.E().hasLabel(\"friend\")",
- "java": "g.E().hasLabel(\"friend\")",
- "javascript": "g.E().hasLabel(\"friend\")",
- "python": "g.E().has_label('friend')"
}
]
},
@@ -43217,16 +43099,16 @@
"scenario": "g_E_dropLabelXknowsX_labels",
"traversals": [
{
- "original": "g.addV(\"person\").as(\"a\").addV(\"person\").as(\"b\").addE(\"knows\", \"trusts\").from(\"a\").to(\"b\")",
- "language": "g.addV(\"person\").as(\"a\").addV(\"person\").as(\"b\").addE(\"knows\", \"trusts\").from(\"a\").to(\"b\")",
- "canonical": "g.addV(\"person\").as(\"a\").addV(\"person\").as(\"b\").addE(\"knows\", \"trusts\").from(\"a\").to(\"b\")",
- "anonymized": "g.addV(string0).as(string1).addV(string0).as(string2).addE(string3, string4).from(string1).to(string2)",
- "dotnet": "g.AddV((string) \"person\").As(\"a\").AddV((string) \"person\").As(\"b\").AddE(\"knows\", \"trusts\").From(\"a\").To(\"b\")",
- "go": "g.AddV(\"person\").As(\"a\").AddV(\"person\").As(\"b\").AddE(\"knows\", \"trusts\").From(\"a\").To(\"b\")",
- "groovy": "g.addV(\"person\").as(\"a\").addV(\"person\").as(\"b\").addE(\"knows\", \"trusts\").from(\"a\").to(\"b\")",
- "java": "g.addV(\"person\").as(\"a\").addV(\"person\").as(\"b\").addE(\"knows\", \"trusts\").from(\"a\").to(\"b\")",
- "javascript": "g.addV(\"person\").as(\"a\").addV(\"person\").as(\"b\").addE(\"knows\", \"trusts\").from_(\"a\").to(\"b\")",
- "python": "g.add_v('person').as_('a').add_v('person').as_('b').add_e('knows', 'trusts').from_('a').to('b')"
+ "original": "g.addV(\"person\").as(\"a\").addV(\"person\").as(\"b\").addE(\"knows\").from(\"a\").to(\"b\")",
+ "language": "g.addV(\"person\").as(\"a\").addV(\"person\").as(\"b\").addE(\"knows\").from(\"a\").to(\"b\")",
+ "canonical": "g.addV(\"person\").as(\"a\").addV(\"person\").as(\"b\").addE(\"knows\").from(\"a\").to(\"b\")",
+ "anonymized": "g.addV(string0).as(string1).addV(string0).as(string2).addE(string3).from(string1).to(string2)",
+ "dotnet": "g.AddV((string) \"person\").As(\"a\").AddV((string) \"person\").As(\"b\").AddE((string) \"knows\").From(\"a\").To(\"b\")",
+ "go": "g.AddV(\"person\").As(\"a\").AddV(\"person\").As(\"b\").AddE(\"knows\").From(\"a\").To(\"b\")",
+ "groovy": "g.addV(\"person\").as(\"a\").addV(\"person\").as(\"b\").addE(\"knows\").from(\"a\").to(\"b\")",
+ "java": "g.addV(\"person\").as(\"a\").addV(\"person\").as(\"b\").addE(\"knows\").from(\"a\").to(\"b\")",
+ "javascript": "g.addV(\"person\").as(\"a\").addV(\"person\").as(\"b\").addE(\"knows\").from_(\"a\").to(\"b\")",
+ "python": "g.add_v('person').as_('a').add_v('person').as_('b').add_e('knows').from_('a').to('b')"
},
{
"original": "g.E().dropLabel(\"knows\").labels().fold()",
@@ -43239,30 +43121,6 @@
"java": "g.E().dropLabel(\"knows\").labels().fold()",
"javascript": "g.E().dropLabel(\"knows\").labels().fold()",
"python": "g.E().drop_label('knows').labels().fold()"
- },
- {
- "original": "g.E().hasLabel(\"knows\")",
- "language": "g.E().hasLabel(\"knows\")",
- "canonical": "g.E().hasLabel(\"knows\")",
- "anonymized": "g.E().hasLabel(string0)",
- "dotnet": "g.E().HasLabel(\"knows\")",
- "go": "g.E().HasLabel(\"knows\")",
- "groovy": "g.E().hasLabel(\"knows\")",
- "java": "g.E().hasLabel(\"knows\")",
- "javascript": "g.E().hasLabel(\"knows\")",
- "python": "g.E().has_label('knows')"
- },
- {
- "original": "g.E().hasLabel(\"trusts\")",
- "language": "g.E().hasLabel(\"trusts\")",
- "canonical": "g.E().hasLabel(\"trusts\")",
- "anonymized": "g.E().hasLabel(string0)",
- "dotnet": "g.E().HasLabel(\"trusts\")",
- "go": "g.E().HasLabel(\"trusts\")",
- "groovy": "g.E().hasLabel(\"trusts\")",
- "java": "g.E().hasLabel(\"trusts\")",
- "javascript": "g.E().hasLabel(\"trusts\")",
- "python": "g.E().has_label('trusts')"
}
]
},
@@ -43270,16 +43128,16 @@
"scenario": "g_E_dropLabels_labels",
"traversals": [
{
- "original": "g.addV(\"person\").as(\"a\").addV(\"person\").as(\"b\").addE(\"knows\", \"trusts\").from(\"a\").to(\"b\")",
- "language": "g.addV(\"person\").as(\"a\").addV(\"person\").as(\"b\").addE(\"knows\", \"trusts\").from(\"a\").to(\"b\")",
- "canonical": "g.addV(\"person\").as(\"a\").addV(\"person\").as(\"b\").addE(\"knows\", \"trusts\").from(\"a\").to(\"b\")",
- "anonymized": "g.addV(string0).as(string1).addV(string0).as(string2).addE(string3, string4).from(string1).to(string2)",
- "dotnet": "g.AddV((string) \"person\").As(\"a\").AddV((string) \"person\").As(\"b\").AddE(\"knows\", \"trusts\").From(\"a\").To(\"b\")",
- "go": "g.AddV(\"person\").As(\"a\").AddV(\"person\").As(\"b\").AddE(\"knows\", \"trusts\").From(\"a\").To(\"b\")",
- "groovy": "g.addV(\"person\").as(\"a\").addV(\"person\").as(\"b\").addE(\"knows\", \"trusts\").from(\"a\").to(\"b\")",
- "java": "g.addV(\"person\").as(\"a\").addV(\"person\").as(\"b\").addE(\"knows\", \"trusts\").from(\"a\").to(\"b\")",
- "javascript": "g.addV(\"person\").as(\"a\").addV(\"person\").as(\"b\").addE(\"knows\", \"trusts\").from_(\"a\").to(\"b\")",
- "python": "g.add_v('person').as_('a').add_v('person').as_('b').add_e('knows', 'trusts').from_('a').to('b')"
+ "original": "g.addV(\"person\").as(\"a\").addV(\"person\").as(\"b\").addE(\"knows\").from(\"a\").to(\"b\")",
+ "language": "g.addV(\"person\").as(\"a\").addV(\"person\").as(\"b\").addE(\"knows\").from(\"a\").to(\"b\")",
+ "canonical": "g.addV(\"person\").as(\"a\").addV(\"person\").as(\"b\").addE(\"knows\").from(\"a\").to(\"b\")",
+ "anonymized": "g.addV(string0).as(string1).addV(string0).as(string2).addE(string3).from(string1).to(string2)",
+ "dotnet": "g.AddV((string) \"person\").As(\"a\").AddV((string) \"person\").As(\"b\").AddE((string) \"knows\").From(\"a\").To(\"b\")",
+ "go": "g.AddV(\"person\").As(\"a\").AddV(\"person\").As(\"b\").AddE(\"knows\").From(\"a\").To(\"b\")",
+ "groovy": "g.addV(\"person\").as(\"a\").addV(\"person\").as(\"b\").addE(\"knows\").from(\"a\").to(\"b\")",
+ "java": "g.addV(\"person\").as(\"a\").addV(\"person\").as(\"b\").addE(\"knows\").from(\"a\").to(\"b\")",
+ "javascript": "g.addV(\"person\").as(\"a\").addV(\"person\").as(\"b\").addE(\"knows\").from_(\"a\").to(\"b\")",
+ "python": "g.add_v('person').as_('a').add_v('person').as_('b').add_e('knows').from_('a').to('b')"
},
{
"original": "g.E().dropLabels().labels()",
diff --git a/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/test/features/map/AddEdge.feature b/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/test/features/map/AddEdge.feature
index 267cefaec9..70058962bc 100644
--- a/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/test/features/map/AddEdge.feature
+++ b/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/test/features/map/AddEdge.feature
@@ -529,35 +529,3 @@ Feature: Step - addE()
"""
When iterated to list
Then the traversal will raise an error with message containing text of "must resolve to a Vertex or the ID of a Vertex present in the graph"
-
- @MultiLabel
- Scenario: g_addEXa_bX_from_V_to_V_labels_fold
- Given the empty graph
- And the graph initializer of
- """
- g.addV("person").property("name", "marko").addV("person").property("name", "josh")
- """
- And the traversal of
- """
- g.addE("knows", "trusts").from(__.V().has("name", "marko")).to(__.V().has("name", "josh")).labels().fold()
- """
- When iterated to list
- Then the result should have a count of 1
- And the graph should return 1 for count of "g.E().hasLabel(\"knows\")"
- And the graph should return 1 for count of "g.E().hasLabel(\"trusts\")"
-
- @MultiLabel
- Scenario: g_addEXa_b_cX_from_V_to_V_labels_count
- Given the empty graph
- And the graph initializer of
- """
- g.addV("person").property("name", "marko").addV("person").property("name", "josh")
- """
- And the traversal of
- """
- g.addE("a", "b", "c").from(__.V().has("name", "marko")).to(__.V().has("name", "josh")).labels().count()
- """
- When iterated to list
- Then the result should be unordered
- | result |
- | d[3].l |
diff --git a/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/test/features/map/MergeVertex.feature b/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/test/features/map/MergeVertex.feature
index 930e3a181b..eb95e6d3e2 100644
--- a/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/test/features/map/MergeVertex.feature
+++ b/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/test/features/map/MergeVertex.feature
@@ -1076,8 +1076,8 @@ Feature: Step - mergeV()
Then the result should have a count of 1
And the graph should return 1 for count of "g.V()"
And the graph should return 1 for count of "g.V().hasLabel(\"manager\")"
- And the graph should return 0 for count of "g.V().hasLabel(\"person\")"
- And the graph should return 0 for count of "g.V().hasLabel(\"employee\")"
+ And the graph should return 1 for count of "g.V().hasLabel(\"person\")"
+ And the graph should return 1 for count of "g.V().hasLabel(\"employee\")"
@MultiLabel
Scenario: g_mergeVXlabel_person_name_markoX_optionXonMatch_label_manager_directorX
@@ -1095,7 +1095,7 @@ Feature: Step - mergeV()
Then the result should have a count of 1
And the graph should return 1 for count of "g.V()"
And the graph should return 1 for count of "g.V().hasLabel(\"manager\").hasLabel(\"director\")"
- And the graph should return 0 for count of "g.V().hasLabel(\"person\")"
+ And the graph should return 1 for count of "g.V().hasLabel(\"person\")"
@MultiLabel
Scenario: g_mergeVXlabel_person_name_markoX_optionXonMatch_label_emptyX
@@ -1112,5 +1112,4 @@ Feature: Step - mergeV()
When iterated to list
Then the result should have a count of 1
And the graph should return 1 for count of "g.V()"
- And the graph should return 1 for count of "g.V().hasLabel(\"vertex\")"
- And the graph should return 0 for count of "g.V().hasLabel(\"person\")"
+ And the graph should return 1 for count of "g.V().hasLabel(\"person\")"
diff --git a/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/test/features/sideEffect/AddLabel.feature b/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/test/features/sideEffect/AddLabel.feature
index 5c0891ebb8..0837669796 100644
--- a/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/test/features/sideEffect/AddLabel.feature
+++ b/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/test/features/sideEffect/AddLabel.feature
@@ -77,6 +77,4 @@ Feature: Step - addLabel()
g.E().addLabel("friend").labels().fold()
"""
When iterated to list
- Then the result should have a count of 1
- And the graph should return 1 for count of "g.E().hasLabel(\"knows\")"
- And the graph should return 1 for count of "g.E().hasLabel(\"friend\")"
+ Then the traversal will raise an error with message containing text of "Cannot add label"
diff --git a/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/test/features/sideEffect/DropLabel.feature b/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/test/features/sideEffect/DropLabel.feature
index 0c60f6c3c0..c96e375cde 100644
--- a/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/test/features/sideEffect/DropLabel.feature
+++ b/gremlin-test/src/main/resources/org/apache/tinkerpop/gremlin/test/features/sideEffect/DropLabel.feature
@@ -46,9 +46,7 @@ Feature: Step - dropLabel() / dropLabels()
g.V().dropLabels().labels()
"""
When iterated to list
- Then the result should be unordered
- | result |
- | vertex |
+ Then the result should have a count of 0
@MultiLabel
Scenario: g_V_dropLabelXa_bX_labels
@@ -78,16 +76,14 @@ Feature: Step - dropLabel() / dropLabels()
g.V().dropLabels().labels()
"""
When iterated to list
- Then the result should be unordered
- | result |
- | vertex |
+ Then the result should have a count of 0
@MultiLabel
Scenario: g_E_dropLabelXknowsX_labels
Given the empty graph
And the graph initializer of
"""
- g.addV("person").as("a").addV("person").as("b").addE("knows", "trusts").from("a").to("b")
+ g.addV("person").as("a").addV("person").as("b").addE("knows").from("a").to("b")
"""
And the traversal of
"""
@@ -95,21 +91,17 @@ Feature: Step - dropLabel() / dropLabels()
"""
When iterated to list
Then the result should have a count of 1
- And the graph should return 0 for count of "g.E().hasLabel(\"knows\")"
- And the graph should return 1 for count of "g.E().hasLabel(\"trusts\")"
@MultiLabel
Scenario: g_E_dropLabels_labels
Given the empty graph
And the graph initializer of
"""
- g.addV("person").as("a").addV("person").as("b").addE("knows", "trusts").from("a").to("b")
+ g.addV("person").as("a").addV("person").as("b").addE("knows").from("a").to("b")
"""
And the traversal of
"""
g.E().dropLabels().labels()
"""
When iterated to list
- Then the result should be unordered
- | result |
- | edge |
+ Then the result should have a count of 0
diff --git a/gremlin-util/src/test/java/org/apache/tinkerpop/gremlin/util/ser/binary/TypeSerializerFailureTests.java b/gremlin-util/src/test/java/org/apache/tinkerpop/gremlin/util/ser/binary/TypeSerializerFailureTests.java
index ad6e18d6bc..469a865d2a 100644
--- a/gremlin-util/src/test/java/org/apache/tinkerpop/gremlin/util/ser/binary/TypeSerializerFailureTests.java
+++ b/gremlin-util/src/test/java/org/apache/tinkerpop/gremlin/util/ser/binary/TypeSerializerFailureTests.java
@@ -57,7 +57,10 @@ public class TypeSerializerFailureTests {
@Parameterized.Parameters(name = "Value={0}")
public static Collection input() {
- final ReferenceVertex vertex = new ReferenceVertex("a vertex", (String) null);
+ // Use an unserializable id (raw Object has no registered TypeSerializer) to force
+ // serialization failure for vertex/edge cases. Previously null labels caused the
+ // failure, but now empty labels are serialized gracefully as empty lists.
+ final ReferenceVertex vertex = new ReferenceVertex(new Object(), "a vertex");
final BulkSet<Object> bulkSet = new BulkSet<>();
bulkSet.add(vertex, 1L);
@@ -72,7 +75,7 @@ public class TypeSerializerFailureTests {
vertex,
bulkSet,
Collections.singletonList(vertex),
- new ReferenceEdge("an edge", (String) null, vertex, vertex),
+ new ReferenceEdge(new Object(), "an edge", vertex, vertex),
Lambda.supplier(null),
metrics,
new DefaultTraversalMetrics(1L, Collections.singletonList(metrics)),
diff --git a/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/AbstractTinkerGraph.java b/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/AbstractTinkerGraph.java
index 5a0abb6d13..4a16f15df0 100644
--- a/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/AbstractTinkerGraph.java
+++ b/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/AbstractTinkerGraph.java
@@ -23,6 +23,7 @@ import org.apache.tinkerpop.gremlin.process.computer.GraphComputer;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Element;
import org.apache.tinkerpop.gremlin.structure.Graph;
+import org.apache.tinkerpop.gremlin.structure.LabelCardinality;
import org.apache.tinkerpop.gremlin.structure.Transaction;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.structure.VertexProperty;
@@ -64,6 +65,8 @@ public abstract class AbstractTinkerGraph implements Graph {
public static final String GREMLIN_TINKERGRAPH_GRAPH_FORMAT = "gremlin.tinkergraph.graphFormat";
public static final String GREMLIN_TINKERGRAPH_ALLOW_NULL_PROPERTY_VALUES = "gremlin.tinkergraph.allowNullPropertyValues";
public static final String GREMLIN_TINKERGRAPH_SERVICE = "gremlin.tinkergraph.service";
+ public static final String GREMLIN_TINKERGRAPH_VERTEX_LABEL_CARDINALITY = "gremlin.tinkergraph.vertexLabelCardinality";
+ public static final String GREMLIN_TINKERGRAPH_EDGE_LABEL_CARDINALITY = "gremlin.tinkergraph.edgeLabelCardinality";
protected AtomicLong currentId = new AtomicLong(-1L);
protected Map<Object, VertexProperty> vertexProperties = new ConcurrentHashMap<>();
@@ -78,6 +81,10 @@ public abstract class AbstractTinkerGraph implements Graph {
protected IdManager<VertexProperty> vertexPropertyIdManager;
protected VertexProperty.Cardinality defaultVertexPropertyCardinality;
protected boolean allowNullPropertyValues;
+ protected LabelCardinality vertexLabelCardinality;
+ protected LabelCardinality edgeLabelCardinality;
+ protected String defaultVertexLabel;
+ protected String defaultEdgeLabel;
protected TinkerServiceRegistry serviceRegistry;
@@ -447,6 +454,16 @@ public abstract class AbstractTinkerGraph implements Graph {
public VertexProperty.Cardinality getCardinality(final String key) {
return defaultVertexPropertyCardinality;
}
+
+ @Override
+ public LabelCardinality getLabelCardinality() {
+ return vertexLabelCardinality;
+ }
+
+ @Override
+ public String getDefaultLabel() {
+ return defaultVertexLabel;
+ }
}
public class TinkerGraphEdgeFeatures implements Features.EdgeFeatures {
@@ -468,6 +485,16 @@ public abstract class AbstractTinkerGraph implements Graph {
public boolean willAllowId(final Object id) {
return edgeIdManager.allow(id);
}
+
+ @Override
+ public LabelCardinality getLabelCardinality() {
+ return edgeLabelCardinality;
+ }
+
+ @Override
+ public String getDefaultLabel() {
+ return defaultEdgeLabel;
+ }
}
public class TinkerGraphVertexPropertyFeatures implements Features.VertexPropertyFeatures {
diff --git a/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerEdge.java b/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerEdge.java
index b37913a0aa..71425ea63e 100644
--- a/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerEdge.java
+++ b/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerEdge.java
@@ -25,6 +25,7 @@ import org.apache.tinkerpop.gremlin.structure.Property;
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.structure.util.ElementHelper;
+import org.apache.tinkerpop.gremlin.structure.util.LabelCardinalityValidator;
import org.apache.tinkerpop.gremlin.structure.util.StringFactory;
import org.apache.tinkerpop.gremlin.util.iterator.IteratorUtils;
@@ -86,7 +87,7 @@ public class TinkerEdge extends TinkerElement implements Edge {
private TinkerEdge(final Object id, AbstractTinkerGraph graph, final Object outVertexId, final String label, final Object inVertexId, final long currentVersion, final Boolean skipIndexUpdate) {
super(id, label, currentVersion);
- this.edgeLabels = new LinkedHashSet<>();
+ this.edgeLabels = ConcurrentHashMap.newKeySet();
this.edgeLabels.add(label);
isTxMode = graph instanceof TinkerTransactionGraph;
this.graph = graph;
@@ -147,50 +148,23 @@ public class TinkerEdge extends TinkerElement implements Edge {
for (final String l : labels) {
ElementHelper.validateLabel(l);
}
- // Remove default label if it was the only label
- if (this.edgeLabels.size() == 1 && this.edgeLabels.contains(Edge.DEFAULT_LABEL)) {
- this.graph.removeEdgeFromAdjacency(this, Edge.DEFAULT_LABEL);
- this.edgeLabels.remove(Edge.DEFAULT_LABEL);
- }
- this.edgeLabels.add(label);
- this.graph.addEdgeToAdjacency(this, label);
- for (final String l : labels) {
- this.edgeLabels.add(l);
- this.graph.addEdgeToAdjacency(this, l);
- }
- this.label = this.edgeLabels.iterator().next();
+
+ LabelCardinalityValidator.validateAdd(this.graph.edgeLabelCardinality, this.edgeLabels, label, labels);
+ // Never reached — validateAdd throws for ONE
}
@Override
public void dropLabels() {
graph.touch(this);
- for (final String l : new LinkedHashSet<>(this.edgeLabels)) {
- this.graph.removeEdgeFromAdjacency(this, l);
- }
- this.edgeLabels.clear();
- this.edgeLabels.add(Edge.DEFAULT_LABEL);
- this.graph.addEdgeToAdjacency(this, Edge.DEFAULT_LABEL);
- this.label = this.edgeLabels.iterator().next();
+ LabelCardinalityValidator.validateDropAll(this.graph.edgeLabelCardinality, this.edgeLabels);
+ // Never reached — validateDropAll throws for ONE
}
@Override
public void dropLabel(final String label, final String... labels) {
graph.touch(this);
- if (this.edgeLabels.contains(label)) {
- this.graph.removeEdgeFromAdjacency(this, label);
- this.edgeLabels.remove(label);
- }
- for (final String l : labels) {
- if (this.edgeLabels.contains(l)) {
- this.graph.removeEdgeFromAdjacency(this, l);
- this.edgeLabels.remove(l);
- }
- }
- if (this.edgeLabels.isEmpty()) {
- this.edgeLabels.add(Edge.DEFAULT_LABEL);
- this.graph.addEdgeToAdjacency(this, Edge.DEFAULT_LABEL);
- }
- this.label = this.edgeLabels.iterator().next();
+ LabelCardinalityValidator.validateDrop(this.graph.edgeLabelCardinality, this.edgeLabels, label, labels);
+ // Never reached — validateDrop throws for ONE
}
@Override
diff --git a/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerGraph.java b/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerGraph.java
index 3b493caa5d..b49c3af063 100644
--- a/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerGraph.java
+++ b/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerGraph.java
@@ -24,6 +24,7 @@ import org.apache.tinkerpop.gremlin.process.traversal.TraversalStrategies;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Element;
import org.apache.tinkerpop.gremlin.structure.Graph;
+import org.apache.tinkerpop.gremlin.structure.LabelCardinality;
import org.apache.tinkerpop.gremlin.structure.Transaction;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.structure.VertexProperty;
@@ -92,6 +93,13 @@ public class TinkerGraph extends AbstractTinkerGraph {
configuration.getString(GREMLIN_TINKERGRAPH_DEFAULT_VERTEX_PROPERTY_CARDINALITY, VertexProperty.Cardinality.single.name()));
allowNullPropertyValues = configuration.getBoolean(GREMLIN_TINKERGRAPH_ALLOW_NULL_PROPERTY_VALUES, false);
+ vertexLabelCardinality = LabelCardinality.valueOf(
+ configuration.getString(GREMLIN_TINKERGRAPH_VERTEX_LABEL_CARDINALITY, LabelCardinality.ZERO_OR_MORE.name()));
+ edgeLabelCardinality = LabelCardinality.valueOf(
+ configuration.getString(GREMLIN_TINKERGRAPH_EDGE_LABEL_CARDINALITY, LabelCardinality.ZERO_OR_ONE.name()));
+ defaultVertexLabel = Vertex.DEFAULT_LABEL;
+ defaultEdgeLabel = Edge.DEFAULT_LABEL;
+
graphLocation = configuration.getString(GREMLIN_TINKERGRAPH_GRAPH_LOCATION, null);
graphFormat = configuration.getString(GREMLIN_TINKERGRAPH_GRAPH_FORMAT, null);
@@ -142,7 +150,7 @@ public class TinkerGraph extends AbstractTinkerGraph {
ElementHelper.legalPropertyKeyValueArray(keyValues);
Object idValue = vertexIdManager.convert(ElementHelper.getIdValue(keyValues).orElse(null));
final Set<String> labels = ElementHelper.getLabelsValue(keyValues).orElse(
- Collections.singleton(Vertex.DEFAULT_LABEL));
+ Collections.singleton(defaultVertexLabel));
if (null != idValue) {
if (this.vertices.containsKey(idValue))
diff --git a/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerTransactionGraph.java b/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerTransactionGraph.java
index a223607fe2..d0b301e50d 100644
--- a/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerTransactionGraph.java
+++ b/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerTransactionGraph.java
@@ -24,6 +24,7 @@ import org.apache.tinkerpop.gremlin.process.traversal.TraversalStrategies;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Element;
import org.apache.tinkerpop.gremlin.structure.Graph;
+import org.apache.tinkerpop.gremlin.structure.LabelCardinality;
import org.apache.tinkerpop.gremlin.structure.Transaction;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.structure.VertexProperty;
@@ -87,6 +88,13 @@ public final class TinkerTransactionGraph extends AbstractTinkerGraph {
configuration.getString(GREMLIN_TINKERGRAPH_DEFAULT_VERTEX_PROPERTY_CARDINALITY, VertexProperty.Cardinality.single.name()));
allowNullPropertyValues = configuration.getBoolean(GREMLIN_TINKERGRAPH_ALLOW_NULL_PROPERTY_VALUES, false);
+ vertexLabelCardinality = LabelCardinality.valueOf(
+ configuration.getString(GREMLIN_TINKERGRAPH_VERTEX_LABEL_CARDINALITY, LabelCardinality.ZERO_OR_MORE.name()));
+ edgeLabelCardinality = LabelCardinality.valueOf(
+ configuration.getString(GREMLIN_TINKERGRAPH_EDGE_LABEL_CARDINALITY, LabelCardinality.ZERO_OR_ONE.name()));
+ defaultVertexLabel = Vertex.DEFAULT_LABEL;
+ defaultEdgeLabel = Edge.DEFAULT_LABEL;
+
graphLocation = configuration.getString(GREMLIN_TINKERGRAPH_GRAPH_LOCATION, null);
graphFormat = configuration.getString(GREMLIN_TINKERGRAPH_GRAPH_FORMAT, null);
@@ -140,7 +148,7 @@ public final class TinkerTransactionGraph extends AbstractTinkerGraph {
if (null == idValue)
idValue = vertexIdManager.getNextId(this);
final Set<String> labels = ElementHelper.getLabelsValue(keyValues).orElse(
- Collections.singleton(Vertex.DEFAULT_LABEL));
+ Collections.singleton(defaultVertexLabel));
this.tx().readWrite();
final long txNumber = transaction.getTxNumber();
diff --git a/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerVertex.java b/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerVertex.java
index f3a97beb13..605519c500 100644
--- a/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerVertex.java
+++ b/tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerVertex.java
@@ -24,12 +24,14 @@ import org.apache.tinkerpop.gremlin.structure.Graph;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.structure.VertexProperty;
import org.apache.tinkerpop.gremlin.structure.util.ElementHelper;
+import org.apache.tinkerpop.gremlin.structure.util.LabelCardinalityValidator;
import org.apache.tinkerpop.gremlin.structure.util.StringFactory;
import org.apache.tinkerpop.gremlin.util.CollectionUtil;
import org.apache.tinkerpop.gremlin.util.iterator.IteratorUtils;
import java.util.ArrayList;
import java.util.Collections;
+import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
@@ -77,25 +79,54 @@ public class TinkerVertex extends TinkerElement implements Vertex {
/**
* Canonical constructor. Constructs a TinkerVertex with multiple labels and a specific version (for transactional graphs).
+ * Uses a single-switch pattern to handle default label injection per the configured cardinality.
*/
protected TinkerVertex(final Object id, final Set<String> labels, final AbstractTinkerGraph graph, final long currentVersion) {
- super(id, (labels == null || labels.isEmpty()) ? Vertex.DEFAULT_LABEL : labels.iterator().next(), currentVersion);
+ super(id, null, currentVersion); // label field set below
this.graph = graph;
this.isTxMode = graph instanceof TinkerTransactionGraph;
this.allowNullPropertyValues = graph.features().vertex().supportsNullPropertyValues();
- this.vertexLabels = (labels == null || labels.isEmpty())
- ? new LinkedHashSet<>(Collections.singleton(Vertex.DEFAULT_LABEL))
- : new LinkedHashSet<>(labels);
+
+ this.vertexLabels = ConcurrentHashMap.newKeySet();
+ switch (graph.vertexLabelCardinality) {
+ case ONE:
+ // Exactly 1 label: use provided or default
+ if (labels != null && !labels.isEmpty())
+ this.vertexLabels.addAll(labels);
+ else
+ this.vertexLabels.add(graph.defaultVertexLabel);
+ break;
+ case ONE_OR_MORE:
+ // Default label always present alongside any user labels
+ this.vertexLabels.add(graph.defaultVertexLabel);
+ if (labels != null) this.vertexLabels.addAll(labels);
+ break;
+ case ZERO_OR_MORE:
+ // Fully flexible — store whatever was provided
+ if (labels != null) this.vertexLabels.addAll(labels);
+ break;
+ }
+
+ // Validate the resulting set conforms to cardinality
+ LabelCardinalityValidator.validateCreation(graph.vertexLabelCardinality, this.vertexLabels);
+
+ this.label = this.vertexLabels.isEmpty() ? "" : this.vertexLabels.iterator().next();
}
@Override
public Set<String> labels() {
+ if (this.vertexLabels.isEmpty()) {
+ return Collections.emptySet();
+ }
return Collections.unmodifiableSet(this.vertexLabels);
}
@Override
@Deprecated
public String label() {
+ if (this.vertexLabels.isEmpty()) {
+ return "";
+ }
return this.vertexLabels.iterator().next();
}
@@ -105,12 +136,8 @@ public class TinkerVertex extends TinkerElement implements Vertex {
for (final String l : labels) {
ElementHelper.validateLabel(l);
}
-
- // Remove default label if it was the only label and we're adding real labels
- if (this.vertexLabels.size() == 1 && this.vertexLabels.contains(Vertex.DEFAULT_LABEL)) {
- this.vertexLabels.remove(Vertex.DEFAULT_LABEL);
- }
-
+ LabelCardinalityValidator.validateAdd(this.graph.vertexLabelCardinality, this.vertexLabels, label, labels);
+ graph.touch(this);
this.vertexLabels.add(label);
Collections.addAll(this.vertexLabels, labels);
this.label = this.vertexLabels.iterator().next();
@@ -119,23 +146,22 @@ public class TinkerVertex extends TinkerElement implements Vertex {
@Override
public void dropLabels() {
+ LabelCardinalityValidator.validateDropAll(this.graph.vertexLabelCardinality, this.vertexLabels);
+ graph.touch(this);
this.vertexLabels.clear();
- this.vertexLabels.add(Vertex.DEFAULT_LABEL);
- this.label = this.vertexLabels.iterator().next();
+ this.label = "";
this.graph.updateVertexLabelIndex(this);
}
@Override
public void dropLabel(final String label, final String... labels) {
+ LabelCardinalityValidator.validateDrop(this.graph.vertexLabelCardinality, this.vertexLabels, label, labels);
+ graph.touch(this);
this.vertexLabels.remove(label);
for (final String l : labels) {
this.vertexLabels.remove(l);
}
-
- if (this.vertexLabels.isEmpty()) {
- this.vertexLabels.add(Vertex.DEFAULT_LABEL);
- }
- this.label = this.vertexLabels.iterator().next();
+ this.label = this.vertexLabels.isEmpty() ? "" : this.vertexLabels.iterator().next();
this.graph.updateVertexLabelIndex(this);
}
@@ -267,6 +293,24 @@ public class TinkerVertex extends TinkerElement implements Vertex {
final List<Edge> edges = new ArrayList<>();
this.edges(Direction.BOTH).forEachRemaining(edge -> edges.add(edge));
edges.stream().filter(edge -> !((TinkerEdge) edge).removed).forEach(Edge::remove);
+
+ // Also remove any orphaned edges from the global edges map that reference this vertex.
+ // Edges can become orphaned from the adjacency maps when their labels are dropped via
+ // dropLabels()/dropLabel(), which removes them from the vertex's outEdges/inEdges but
+ // leaves them in the graph's global edges map.
+ final Object thisId = this.id();
+ final List<Object> orphanedEdgeIds = new ArrayList<>();
+ graph.edges().forEachRemaining(edge -> {
+ if (!((TinkerEdge) edge).removed) {
+ if (edge.outVertex().id().equals(thisId) || edge.inVertex().id().equals(thisId)) {
+ orphanedEdgeIds.add(edge.id());
+ }
+ }
+ });
+ for (final Object edgeId : orphanedEdgeIds) {
+ graph.removeEdge(edgeId);
+ }
+
TinkerIndexHelper.removeElementIndex(this);
if (null != this.properties)
this.properties.values().forEach(vpList -> vpList.forEach(vp -> graph.vertexProperties.remove(vp.id())));
diff --git a/tinkergraph-gremlin/src/test/java/org/apache/tinkerpop/gremlin/tinkergraph/process/traversal/step/map/MergeVMultiLabelTest.java b/tinkergraph-gremlin/src/test/java/org/apache/tinkerpop/gremlin/tinkergraph/process/traversal/step/map/MergeVMultiLabelTest.java
index 2257a15b60..c64996ee35 100644
--- a/tinkergraph-gremlin/src/test/java/org/apache/tinkerpop/gremlin/tinkergraph/process/traversal/step/map/MergeVMultiLabelTest.java
+++ b/tinkergraph-gremlin/src/test/java/org/apache/tinkerpop/gremlin/tinkergraph/process/traversal/step/map/MergeVMultiLabelTest.java
@@ -23,6 +23,7 @@ import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSo
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
+import org.apache.tinkerpop.gremlin.tinkergraph.structure.AbstractTinkerGraph;
import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph;
import org.junit.After;
import org.junit.Before;
@@ -50,7 +51,10 @@ public class MergeVMultiLabelTest {
@Before
public void setup() {
- graph = TinkerGraph.open();
+ final org.apache.commons.configuration2.Configuration config = new org.apache.commons.configuration2.BaseConfiguration();
+ config.setProperty(Graph.GRAPH, TinkerGraph.class.getName());
+ config.setProperty(AbstractTinkerGraph.GREMLIN_TINKERGRAPH_VERTEX_LABEL_CARDINALITY, "ZERO_OR_MORE");
+ graph = TinkerGraph.open(config);
g = graph.traversal();
}
@@ -117,38 +121,39 @@ public class MergeVMultiLabelTest {
// --- mergeV onMatch label replacement ---
@Test
- public void shouldReplaceLabelsOnMatchWithSingleLabel() {
+ public void shouldAppendLabelsOnMatchWithSingleLabel() {
final Vertex v = g.addV("person").addLabel("employee").property("name", "marko").next();
g.mergeV(Map.of(T.label, "person", "name", "marko"))
.option(Merge.onMatch, Map.of(T.label, "manager")).next();
- // labels should be wholly replaced
- assertThat(v.labels(), hasSize(1));
- assertThat(v.labels(), containsInAnyOrder("manager"));
+ // labels should be appended (addLabel semantics), not replaced
+ assertThat(v.labels(), hasSize(3));
+ assertThat(v.labels(), containsInAnyOrder("person", "employee", "manager"));
}
@Test
- public void shouldReplaceLabelsOnMatchWithMultiLabel() {
+ public void shouldAppendLabelsOnMatchWithMultiLabel() {
final Vertex v = g.addV("person").property("name", "marko").next();
final Set<String> newLabels = new LinkedHashSet<>(Arrays.asList("manager", "director"));
g.mergeV(Map.of(T.label, "person", "name", "marko"))
.option(Merge.onMatch, Map.of(T.label, newLabels)).next();
- assertThat(v.labels(), hasSize(2));
- assertThat(v.labels(), containsInAnyOrder("manager", "director"));
+ // labels should be appended (addLabel semantics)
+ assertThat(v.labels(), hasSize(3));
+ assertThat(v.labels(), containsInAnyOrder("person", "manager", "director"));
}
@Test
- public void shouldApplyDefaultLabelOnMatchWithEmptyCollection() {
+ public void shouldNoOpOnMatchWithEmptyCollection() {
final Vertex v = g.addV("person").property("name", "marko").next();
g.mergeV(Map.of(T.label, "person", "name", "marko"))
.option(Merge.onMatch, Map.of(T.label, Collections.emptySet())).next();
- // empty collection triggers default label behavior
+ // Empty collection = nothing to add, labels unchanged
assertThat(v.labels(), hasSize(1));
- assertThat(v.labels(), containsInAnyOrder(Vertex.DEFAULT_LABEL));
+ assertThat(v.labels(), containsInAnyOrder("person"));
}
}
diff --git a/tinkergraph-gremlin/src/test/java/org/apache/tinkerpop/gremlin/tinkergraph/process/traversal/step/sideEffect/LabelMutationPropertyTest.java b/tinkergraph-gremlin/src/test/java/org/apache/tinkerpop/gremlin/tinkergraph/process/traversal/step/sideEffect/LabelMutationPropertyTest.java
index 5aeea9daa8..d9f19e490f 100644
--- a/tinkergraph-gremlin/src/test/java/org/apache/tinkerpop/gremlin/tinkergraph/process/traversal/step/sideEffect/LabelMutationPropertyTest.java
+++ b/tinkergraph-gremlin/src/test/java/org/apache/tinkerpop/gremlin/tinkergraph/process/traversal/step/sideEffect/LabelMutationPropertyTest.java
@@ -23,6 +23,7 @@ import org.apache.tinkerpop.gremlin.process.traversal.step.util.WithOptions;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
+import org.apache.tinkerpop.gremlin.tinkergraph.structure.AbstractTinkerGraph;
import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph;
import org.junit.After;
import org.junit.Before;
@@ -59,7 +60,10 @@ public class LabelMutationPropertyTest {
@Before
public void setup() {
- graph = TinkerGraph.open();
+ final org.apache.commons.configuration2.Configuration config = new org.apache.commons.configuration2.BaseConfiguration();
+ config.setProperty(Graph.GRAPH, TinkerGraph.class.getName());
+ config.setProperty(AbstractTinkerGraph.GREMLIN_TINKERGRAPH_VERTEX_LABEL_CARDINALITY, "ZERO_OR_MORE");
+ graph = TinkerGraph.open(config);
g = graph.traversal();
random = new Random(42); // deterministic seed for reproducibility
}
@@ -133,10 +137,9 @@ public class LabelMutationPropertyTest {
// drop all labels
g.V(v).dropLabels().iterate();
- assertThat("Iteration " + i + ": after dropLabels(), vertex should have exactly one label",
- v.labels(), hasSize(1));
- assertThat("Iteration " + i + ": after dropLabels(), vertex should have default label",
- v.labels(), containsInAnyOrder(Vertex.DEFAULT_LABEL));
+ // Under ZERO_OR_MORE cardinality, dropping all labels results in empty set
+ assertThat("Iteration " + i + ": after dropLabels(), vertex should have no labels",
+ v.labels(), hasSize(0));
}
}
@@ -171,7 +174,7 @@ public class LabelMutationPropertyTest {
/**
* Property 12: ValueMap/ElementMap multilabel configuration.
- * For any element with labels L, valueMap(true).with(WithOptions.multilabel) shall return
+ * For any element with labels L, g.with("multilabel").V(v).valueMap(true) shall return
* labels as Set<String> equal to L, and without the config shall return a single String from L.
*/
@SuppressWarnings("unchecked")
@@ -185,8 +188,8 @@ public class LabelMutationPropertyTest {
}
// with multilabel config: should return Set<String>
- final Map<Object, Object> mapWithConfig = g.V(v).valueMap(true)
- .with(WithOptions.multilabel).next();
+ final GraphTraversalSource gml = g.with("multilabel");
+ final Map<Object, Object> mapWithConfig = gml.V(v).valueMap(true).next();
final Object labelWithConfig = mapWithConfig.get(T.label);
assertThat("Iteration " + i + ": with multilabel config, label should be a Set",
labelWithConfig, instanceOf(Set.class));
diff --git a/tinkergraph-gremlin/src/test/java/org/apache/tinkerpop/gremlin/tinkergraph/process/traversal/step/sideEffect/LabelMutationStepTest.java b/tinkergraph-gremlin/src/test/java/org/apache/tinkerpop/gremlin/tinkergraph/process/traversal/step/sideEffect/LabelMutationStepTest.java
index 7ac5c88015..1c1d727a83 100644
--- a/tinkergraph-gremlin/src/test/java/org/apache/tinkerpop/gremlin/tinkergraph/process/traversal/step/sideEffect/LabelMutationStepTest.java
+++ b/tinkergraph-gremlin/src/test/java/org/apache/tinkerpop/gremlin/tinkergraph/process/traversal/step/sideEffect/LabelMutationStepTest.java
@@ -24,6 +24,7 @@ import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
+import org.apache.tinkerpop.gremlin.tinkergraph.structure.AbstractTinkerGraph;
import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph;
import org.junit.After;
import org.junit.Before;
@@ -51,7 +52,10 @@ public class LabelMutationStepTest {
@Before
public void setup() {
- graph = TinkerGraph.open();
+ final org.apache.commons.configuration2.Configuration config = new org.apache.commons.configuration2.BaseConfiguration();
+ config.setProperty(Graph.GRAPH, TinkerGraph.class.getName());
+ config.setProperty(AbstractTinkerGraph.GREMLIN_TINKERGRAPH_VERTEX_LABEL_CARDINALITY, "ZERO_OR_MORE");
+ graph = TinkerGraph.open(config);
g = graph.traversal();
}
@@ -78,14 +82,13 @@ public class LabelMutationStepTest {
assertThat(v.labels(), containsInAnyOrder("person", "manager"));
}
- @Test
+ @Test(expected = IllegalStateException.class)
public void shouldAddLabelToEdgeViaTraversal() {
final Vertex v1 = g.addV("person").next();
final Vertex v2 = g.addV("person").next();
final Edge e = v1.addEdge("knows", v2);
+ // Under ZERO_OR_ONE cardinality for edges, adding a second label throws
g.E().addLabel("friend").iterate();
- assertThat(e.labels(), hasSize(2));
- assertThat(e.labels(), containsInAnyOrder("knows", "friend"));
}
// --- dropLabel step tests ---
@@ -102,8 +105,8 @@ public class LabelMutationStepTest {
public void shouldDropAllLabelsViaTraversal() {
final Vertex v = g.addV("person").addLabel("employee").next();
g.V(v).dropLabels().iterate();
- assertThat(v.labels(), hasSize(1));
- assertThat(v.labels(), containsInAnyOrder(Vertex.DEFAULT_LABEL));
+ // Under ZERO_OR_MORE cardinality, dropping all labels results in empty set
+ assertThat(v.labels(), hasSize(0));
}
@Test
@@ -114,14 +117,13 @@ public class LabelMutationStepTest {
assertThat(v.labels(), containsInAnyOrder("employee"));
}
- @Test
+ @Test(expected = IllegalStateException.class)
public void shouldDropLabelsOnEdgeViaTraversal() {
final Vertex v1 = g.addV("person").next();
final Vertex v2 = g.addV("person").next();
final Edge e = v1.addEdge("knows", v2);
+ // Edge cardinality is always ONE — dropLabels() throws
g.E().dropLabels().iterate();
- assertThat(e.labels(), hasSize(1));
- assertThat(e.labels(), containsInAnyOrder(Edge.DEFAULT_LABEL));
}
// --- addV multi-label tests ---
@@ -136,8 +138,8 @@ public class LabelMutationStepTest {
@Test
public void shouldCreateVertexWithDefaultLabelViaAddV() {
final Vertex v = g.addV().next();
- assertThat(v.labels(), hasSize(1));
- assertThat(v.labels(), containsInAnyOrder(Vertex.DEFAULT_LABEL));
+ // Under ZERO_OR_MORE cardinality, addV() with no label produces an empty label set
+ assertThat(v.labels(), hasSize(0));
}
// --- hasLabel index consistency tests ---
@@ -180,8 +182,8 @@ public class LabelMutationStepTest {
@Test
public void shouldReturnLabelsAsSetWithMultilabelConfig() {
final Vertex v = g.addV("person").addLabel("employee").next();
- final Map<Object, Object> map = g.V(v).valueMap(true)
- .with(WithOptions.multilabel).next();
+ final GraphTraversalSource gml = g.with("multilabel");
+ final Map<Object, Object> map = gml.V(v).valueMap(true).next();
final Object labelValue = map.get(T.label);
assertThat(labelValue, instanceOf(Set.class));
final Set<String> labels = (Set<String>) labelValue;
@@ -223,8 +225,8 @@ public class LabelMutationStepTest {
@Test
public void shouldReturnLabelsAsSetWithElementMapMultilabelConfig() {
final Vertex v = g.addV("person").addLabel("employee").next();
- final Map<Object, Object> map = g.V(v).elementMap()
- .with(WithOptions.multilabel).next();
+ final GraphTraversalSource gml = g.with("multilabel");
+ final Map<Object, Object> map = gml.V(v).elementMap().next();
final Object labelValue = map.get(T.label);
assertThat(labelValue, instanceOf(Set.class));
final Set<String> labels = (Set<String>) labelValue;
@@ -246,4 +248,48 @@ public class LabelMutationStepTest {
assertThat(v.labels(), hasSize(3));
assertThat(v.labels(), containsInAnyOrder("person", "employee", "manager"));
}
+
+ // --- null/empty label argument validation ---
+
+ @Test(expected = IllegalArgumentException.class)
+ public void shouldThrowOnAddLabelNull() {
+ final Vertex v = g.addV("person").next();
+ v.addLabel(null);
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void shouldThrowOnAddLabelEmpty() {
+ final Vertex v = g.addV("person").next();
+ v.addLabel("");
+ }
+
+ // --- hasLabel OR semantics on multi-label vertex ---
+
+ @Test
+ public void shouldMatchHasLabelOrSemanticsOnMultiLabelVertex() {
+ g.addV("person").addLabel("employee").next();
+ // hasLabel("person", "nonexistent") is OR — should match because vertex has "person"
+ assertThat(g.V().hasLabel("person", "nonexistent").toList(), hasSize(1));
+ }
+
+ @Test
+ public void shouldMatchHasLabelAndSemanticsOnMultiLabelVertex() {
+ g.addV("person").addLabel("employee").next();
+ // hasLabel("person").hasLabel("employee") is AND — vertex has both
+ assertThat(g.V().hasLabel("person").hasLabel("employee").toList(), hasSize(1));
+ // hasLabel("person").hasLabel("nonexistent") is AND — vertex doesn't have "nonexistent"
+ assertThat(g.V().hasLabel("person").hasLabel("nonexistent").toList(), hasSize(0));
+ }
+
+ // --- index consistency: add → drop → re-add cycle ---
+
+ @Test
+ public void shouldMaintainIndexConsistencyAfterReaddCycle() {
+ final Vertex v = g.addV("person").addLabel("employee").next();
+ assertThat(g.V().hasLabel("employee").toList(), hasSize(1));
+ g.V(v).dropLabel("employee").iterate();
+ assertThat(g.V().hasLabel("employee").toList(), hasSize(0));
+ g.V(v).addLabel("employee").iterate();
+ assertThat(g.V().hasLabel("employee").toList(), hasSize(1));
+ }
}
diff --git a/tinkergraph-gremlin/src/test/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/LabelReplacePatternValidationTest.java b/tinkergraph-gremlin/src/test/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/LabelReplacePatternValidationTest.java
new file mode 100644
index 0000000000..4d69bff117
--- /dev/null
+++ b/tinkergraph-gremlin/src/test/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/LabelReplacePatternValidationTest.java
@@ -0,0 +1,264 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tinkerpop.gremlin.tinkergraph.structure;
+
+import org.apache.tinkerpop.gremlin.process.traversal.Merge;
+import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
+import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__;
+import org.apache.tinkerpop.gremlin.structure.Graph;
+import org.apache.tinkerpop.gremlin.structure.T;
+import org.apache.tinkerpop.gremlin.structure.Vertex;
+import org.apache.tinkerpop.gremlin.tinkergraph.structure.AbstractTinkerGraph;
+import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.util.Arrays;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.containsInAnyOrder;
+import static org.hamcrest.Matchers.empty;
+import static org.hamcrest.Matchers.hasSize;
+import static org.junit.Assert.assertEquals;
+
+/**
+ * Validation tests for label replace/swap/clear workaround patterns
+ * with multi-label support on TinkerGraph (ZERO_OR_MORE vertex cardinality).
+ *
+ * These tests validate that common user patterns for replacing labels work
+ * correctly in the context of the append-only onMatch T.label semantics.
+ */
+public class LabelReplacePatternValidationTest {
+
+ private Graph graph;
+ private GraphTraversalSource g;
+
+ @Before
+ public void setup() {
+ final org.apache.commons.configuration2.Configuration config = new org.apache.commons.configuration2.BaseConfiguration();
+ config.setProperty(Graph.GRAPH, TinkerGraph.class.getName());
+ config.setProperty(AbstractTinkerGraph.GREMLIN_TINKERGRAPH_VERTEX_LABEL_CARDINALITY, "ZERO_OR_MORE");
+ graph = TinkerGraph.open(config);
+ g = graph.traversal();
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ graph.close();
+ }
+
+ // =====================================================
+ // Pattern 1: Replace all labels via post-merge chaining
+ // =====================================================
+
+ @Test
+ public void pattern1_replaceAllLabelsPostMerge() {
+ // Setup: vertex with labels [person, employee]
+ g.addV("person").property("name", "marko").addLabel("employee").iterate();
+
+ // Verify initial state
+ final Set<String> before = g.V().has("name", "marko").next().labels();
+ assertThat(before, hasSize(2));
+ assertThat(before, containsInAnyOrder("person", "employee"));
+
+ // Verify mergeV can find it
+ final Vertex merged = g.mergeV(new LinkedHashMap<>(Map.of("name", "marko"))).next();
+ assertEquals("marko", merged.value("name"));
+
+ // Pattern: dropLabels() then addLabel() after merge
+ g.V().has("name", "marko").dropLabels().addLabel("manager").iterate();
+
+ // Verify result
+ final Set<String> after = g.V().has("name", "marko").next().labels();
+ assertThat(after, hasSize(1));
+ assertThat(after, containsInAnyOrder("manager"));
+ }
+
+ // =====================================================
+ // Pattern 2: Replace specific label
+ // =====================================================
+
+ @Test
+ public void pattern2_replaceSpecificLabel() {
+ // Setup: vertex with labels [person, employee]
+ g.addV("person").property("name", "josh").addLabel("employee").iterate();
+
+ // Verify initial state
+ final Set<String> before = g.V().has("name", "josh").next().labels();
+ assertThat(before, hasSize(2));
+ assertThat(before, containsInAnyOrder("person", "employee"));
+
+ // Pattern: dropLabel("employee") then addLabel("manager")
+ g.V().has("name", "josh").dropLabel("employee").addLabel("manager").iterate();
+
+ // Verify result: person remains, employee replaced with manager
+ final Set<String> after = g.V().has("name", "josh").next().labels();
+ assertThat(after, hasSize(2));
+ assertThat(after, containsInAnyOrder("person", "manager"));
+ }
+
+ // =====================================================
+ // Pattern 3: Clear all labels
+ // =====================================================
+
+ @Test
+ public void pattern3_clearAllLabels() {
+ // Setup: vertex with label [person]
+ g.addV("person").property("name", "vadas").iterate();
+
+ // Verify initial state
+ final Set<String> before = g.V().has("name", "vadas").next().labels();
+ assertThat(before, hasSize(1));
+ assertThat(before, containsInAnyOrder("person"));
+
+ // Pattern: dropLabels() to clear all
+ g.V().has("name", "vadas").dropLabels().iterate();
+
+ // Verify result: empty label set (ZERO_OR_MORE cardinality allows this)
+ final Set<String> after = g.V().has("name", "vadas").next().labels();
+ assertThat(after, empty());
+ }
+
+ // =====================================================
+ // Pattern 4: mergeV then replace labels on match
+ // =====================================================
+
+ @Test
+ public void pattern4_mergeVThenReplaceLabelsOnMatch() {
+ // Setup: vertex with label [person]
+ g.addV("person").property("name", "marko").iterate();
+
+ // Verify initial state
+ final Set<String> before = g.V().has("name", "marko").next().labels();
+ assertThat(before, hasSize(1));
+ assertThat(before, containsInAnyOrder("person"));
+
+ // Pattern: mergeV finds the vertex, then chain dropLabels().addLabel()
+ final Map<Object, Object> mergeMap = new LinkedHashMap<>();
+ mergeMap.put(T.label, "person");
+ mergeMap.put("name", "marko");
+ g.mergeV(mergeMap).dropLabels().addLabel("manager").iterate();
+
+ // Verify result
+ final Set<String> after = g.V().has("name", "marko").next().labels();
+ assertThat(after, hasSize(1));
+ assertThat(after, containsInAnyOrder("manager"));
+ }
+
+ // =====================================================
+ // Pattern 5: onMatch with T.label is APPEND-ONLY
+ // =====================================================
+
+ @Test
+ public void pattern5_onMatchTLabelAppendsOnly() {
+ // Setup: vertex with label [person]
+ g.addV("person").property("name", "alex").iterate();
+
+ // onMatch with T.label adds to existing labels, does NOT replace
+ final Map<Object, Object> mergeMap = new LinkedHashMap<>();
+ mergeMap.put(T.label, "person");
+ mergeMap.put("name", "alex");
+
+ final Map<Object, Object> onMatchMap = new LinkedHashMap<>();
+ onMatchMap.put(T.label, "manager");
+
+ g.mergeV(mergeMap).option(Merge.onMatch, onMatchMap).iterate();
+
+ // Result: labels are [person, manager] — "manager" was appended
+ final Set<String> after = g.V().has("name", "alex").next().labels();
+ assertThat(after, hasSize(2));
+ assertThat(after, containsInAnyOrder("person", "manager"));
+ }
+
+ // =====================================================
+ // =====================================================
+ // Pattern 8: mergeV + dropLabels + addLabel with sideEffect pattern
+ // (label replace using sideEffect within the traversal)
+ // =====================================================
+
+ @Test
+ public void pattern8_labelReplaceViaSideEffectInTraversal() {
+ // Setup: vertex with labels [person, employee]
+ g.addV("person").property("name", "dana").addLabel("employee").iterate();
+
+ // Pattern: use sideEffect to perform mutation inline
+ g.V().has("name", "dana").sideEffect(__.dropLabels()).addLabel("manager").iterate();
+
+ // Verify result
+ final Set<String> after = g.V().has("name", "dana").next().labels();
+ assertThat(after, hasSize(1));
+ assertThat(after, containsInAnyOrder("manager"));
+ }
+
+ // =====================================================
+ // Pattern 9: Conditional label replace using choose()
+ // =====================================================
+
+ @Test
+ public void pattern9_conditionalLabelReplace() {
+ // Setup: vertex with labels [person, temp_worker]
+ g.addV("person").property("name", "bob").addLabel("temp_worker").iterate();
+
+ // Pattern: if has "temp_worker" label, swap to "permanent"
+ g.V().has("name", "bob").
+ choose(__.hasLabel("temp_worker"),
+ __.dropLabel("temp_worker").addLabel("permanent")).
+ iterate();
+
+ // Verify result: person kept, temp_worker -> permanent
+ final Set<String> after = g.V().has("name", "bob").next().labels();
+ assertThat(after, hasSize(2));
+ assertThat(after, containsInAnyOrder("person", "permanent"));
+ }
+
+ // =====================================================
+ // Pattern 10: onMatch with sideEffect for label drop+add
+ // (demonstrates that sideEffect traversal in onMatch can
+ // mutate labels, but the Map returned still uses append)
+ // =====================================================
+
+ @Test
+ public void pattern10_onMatchSideEffectForLabelMutation() {
+ // Setup: vertex with labels [person, employee]
+ g.addV("person").property("name", "eve").addLabel("employee").iterate();
+
+ // The onMatch option traversal can use sideEffect to mutate labels
+ // but the final Map returned (empty here) doesn't touch labels
+ final Map<Object, Object> mergeMap = new LinkedHashMap<>();
+ mergeMap.put(T.label, "person");
+ mergeMap.put("name", "eve");
+
+ final Map<String, Object> emptyMatch = new LinkedHashMap<>();
+
+ g.withSideEffect("m", emptyMatch).
+ mergeV(mergeMap).
+ option(Merge.onMatch, __.sideEffect(__.dropLabels().addLabel("manager")).select("m")).
+ iterate();
+
+ // Verify: labels should be [manager] because sideEffect ran drop+add
+ final Set<String> after = g.V().has("name", "eve").next().labels();
+ assertThat(after, hasSize(1));
+ assertThat(after, containsInAnyOrder("manager"));
+ }
+}
diff --git a/tinkergraph-gremlin/src/test/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerVertexMultiLabelTest.java b/tinkergraph-gremlin/src/test/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerVertexMultiLabelTest.java
index 27387d60e9..e9da6dc2bf 100644
--- a/tinkergraph-gremlin/src/test/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerVertexMultiLabelTest.java
+++ b/tinkergraph-gremlin/src/test/java/org/apache/tinkerpop/gremlin/tinkergraph/structure/TinkerVertexMultiLabelTest.java
@@ -22,6 +22,8 @@ import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSo
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.apache.tinkerpop.gremlin.structure.Vertex;
+import org.apache.tinkerpop.gremlin.tinkergraph.structure.AbstractTinkerGraph;
+import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@@ -43,7 +45,10 @@ public class TinkerVertexMultiLabelTest {
@Before
public void setup() {
- graph = TinkerGraph.open();
+ final org.apache.commons.configuration2.Configuration config = new org.apache.commons.configuration2.BaseConfiguration();
+ config.setProperty(Graph.GRAPH, TinkerGraph.class.getName());
+ config.setProperty(AbstractTinkerGraph.GREMLIN_TINKERGRAPH_VERTEX_LABEL_CARDINALITY, "ZERO_OR_MORE");
+ graph = TinkerGraph.open(config);
g = graph.traversal();
}
@@ -69,8 +74,8 @@ public class TinkerVertexMultiLabelTest {
@Test
public void shouldCreateVertexWithDefaultLabelWhenNoneSpecified() {
final Vertex v = g.addV().next();
- assertThat(v.labels(), hasSize(1));
- assertThat(v.labels(), containsInAnyOrder(Vertex.DEFAULT_LABEL));
+ // Under ZERO_OR_MORE cardinality, addV() with no label produces an empty label set
+ assertThat(v.labels(), hasSize(0));
}
@SuppressWarnings("deprecation")
@@ -119,8 +124,8 @@ public class TinkerVertexMultiLabelTest {
public void shouldDropAllLabelsAndAssignDefault() {
final Vertex v = g.addV("person").addLabel("employee").next();
v.dropLabels();
- assertThat(v.labels(), hasSize(1));
- assertThat(v.labels(), containsInAnyOrder(Vertex.DEFAULT_LABEL));
+ // Under ZERO_OR_MORE cardinality, dropping all labels results in empty set (no virtual default)
+ assertThat(v.labels(), hasSize(0));
}
@Test
@@ -143,28 +148,26 @@ public class TinkerVertexMultiLabelTest {
public void shouldAssignDefaultWhenDroppingLastSpecificLabel() {
final Vertex v = g.addV("person").next();
v.dropLabel("person");
- assertThat(v.labels(), hasSize(1));
- assertThat(v.labels(), containsInAnyOrder(Vertex.DEFAULT_LABEL));
+ // Under ZERO_OR_MORE cardinality, dropping last label results in empty set (no virtual default)
+ assertThat(v.labels(), hasSize(0));
}
- @Test
+ @Test(expected = IllegalStateException.class)
public void shouldAddLabelToEdge() {
final Vertex v1 = g.addV("person").next();
final Vertex v2 = g.addV("person").next();
final Edge e = v1.addEdge("knows", v2);
+ // Under ZERO_OR_ONE cardinality for edges, adding a second label throws
e.addLabel("friend");
- assertThat(e.labels(), hasSize(2));
- assertThat(e.labels(), containsInAnyOrder("knows", "friend"));
}
- @Test
+ @Test(expected = IllegalStateException.class)
public void shouldDropLabelsOnEdge() {
final Vertex v1 = g.addV("person").next();
final Vertex v2 = g.addV("person").next();
final Edge e = v1.addEdge("knows", v2);
+ // Edge cardinality is always ONE — dropLabels() throws
e.dropLabels();
- assertThat(e.labels(), hasSize(1));
- assertThat(e.labels(), containsInAnyOrder(Edge.DEFAULT_LABEL));
}
@Test
@@ -177,9 +180,10 @@ public class TinkerVertexMultiLabelTest {
}
@Test
- public void shouldRemoveDefaultLabelWhenAddingFirstRealLabel() {
+ public void shouldAddLabelToExistingVertexWithDefaultLabel() {
+ // Under ZERO_OR_MORE, addV() assigns no labels. Adding "person" creates a single-label set.
final Vertex v = g.addV().next();
- assertThat(v.labels(), containsInAnyOrder(Vertex.DEFAULT_LABEL));
+ assertThat(v.labels(), hasSize(0));
v.addLabel("person");
assertThat(v.labels(), hasSize(1));
assertThat(v.labels(), containsInAnyOrder("person"));