forked from apache/incubator-hugegraph
-
Notifications
You must be signed in to change notification settings - Fork 11
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Cherry pick cypher support #463
Merged
zhoney
merged 6 commits into
starhugegraph:gh-dis-release
from
xhtian95:cherry_pick_cypher_support
Jun 17, 2022
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
09c5b81
feat: support query data by use cypher language (#1866)
jadepeng eac47ac
fix checkstyle : CypherApiTest (#1877)
JackyYangPassion 2b5c130
modify cypherapi to support query under different graphspaces
9227dc4
Merge branch 'gh-dis-release' into cherry_pick_cypher_support
11c6e7f
add cypherApiTest to ApiTestSuite.java
5e5a811
delete a redundant print statement in CypherApiTest.java
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
97 changes: 97 additions & 0 deletions
97
hugegraph-api/src/main/java/com/baidu/hugegraph/api/gremlin/CypherAPI.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,97 @@ | ||
package com.baidu.hugegraph.api.gremlin; | ||
|
||
import org.opencypher.gremlin.translation.TranslationFacade; | ||
import org.slf4j.Logger; | ||
|
||
import com.baidu.hugegraph.api.filter.CompressInterceptor; | ||
import com.baidu.hugegraph.util.E; | ||
import com.baidu.hugegraph.util.Log; | ||
import com.codahale.metrics.annotation.Timed; | ||
|
||
import javax.inject.Singleton; | ||
import javax.ws.rs.Consumes; | ||
import javax.ws.rs.GET; | ||
import javax.ws.rs.POST; | ||
import javax.ws.rs.Path; | ||
import javax.ws.rs.PathParam; | ||
import javax.ws.rs.Produces; | ||
import javax.ws.rs.QueryParam; | ||
import javax.ws.rs.core.Context; | ||
import javax.ws.rs.core.HttpHeaders; | ||
import javax.ws.rs.core.Response; | ||
|
||
@Path("graphspaces/{graphspace}/graphs/{graph}/cypher") | ||
@Singleton | ||
public class CypherAPI extends GremlinQueryAPI { | ||
|
||
private static final Logger LOG = Log.logger(CypherAPI.class); | ||
|
||
|
||
@GET | ||
@Timed | ||
@CompressInterceptor.Compress(buffer = (1024 * 40)) | ||
@Produces(APPLICATION_JSON_WITH_CHARSET) | ||
public Response query(@Context HttpHeaders headers, | ||
@PathParam("graphspace") String graphspace, | ||
@PathParam("graph") String graph, | ||
@QueryParam("cypher") String cypher) { | ||
|
||
return this.queryByCypher(headers, graphspace, graph, cypher); | ||
} | ||
|
||
@POST | ||
@Timed | ||
@CompressInterceptor.Compress | ||
@Consumes(APPLICATION_JSON) | ||
@Produces(APPLICATION_JSON_WITH_CHARSET) | ||
public Response post(@Context HttpHeaders headers, | ||
@PathParam("graphspace") String graphspace, | ||
@PathParam("graph") String graph, | ||
String cypher) { | ||
|
||
return this.queryByCypher(headers, graphspace, graph, cypher); | ||
} | ||
|
||
private Response queryByCypher(HttpHeaders headers, String graphspace, | ||
String graph, String cypher) { | ||
|
||
E.checkArgument(graphspace != null && !graphspace.isEmpty(), | ||
"The graphspace parameter can't be null or empty"); | ||
E.checkArgument(graph != null && !graph.isEmpty(), | ||
"The graph parameter can't be null or empty"); | ||
E.checkArgument(cypher != null && !cypher.isEmpty(), | ||
"The cypher parameter can't be null or empty"); | ||
String gremlin = this.translateCypher2Gremlin(cypher); | ||
LOG.debug("translated gremlin is {}", gremlin); | ||
String auth = headers.getHeaderString(HttpHeaders.AUTHORIZATION); | ||
String graphInfo = graphspace + "-" + graph; | ||
String gremlinQuery = "{" | ||
+ "\"gremlin\":\"" + gremlin + "\"," | ||
+ "\"bindings\":{}," | ||
+ "\"language\":\"gremlin-groovy\"," | ||
+ "\"aliases\":{\"graph\":" + "\"" + graphInfo + "\"" + | ||
", \"g\":\"__g_" + graphInfo + "\"" + "}}"; | ||
Response response = this.client().doPostRequest(auth, gremlinQuery); | ||
return transformResponseIfNeeded(response); | ||
} | ||
|
||
private String translateCypher2Gremlin(String cypher) { | ||
TranslationFacade translator = new TranslationFacade(); | ||
String gremlin = translator.toGremlinGroovy(cypher); | ||
gremlin = this.buildQueryableGremlin(gremlin); | ||
return gremlin; | ||
} | ||
|
||
private String buildQueryableGremlin(String gremlin) { | ||
/* | ||
* `CREATE (a:person { name : 'test', age: 20) return a` | ||
* would be translated to: | ||
* `g.addV('person').as('a').property(single, 'name', 'test') ...`, | ||
* but hugegraph don't support `.property(single, k, v)`, | ||
* so we replace it to `.property(k, v)` here | ||
*/ | ||
gremlin = gremlin.replace(".property(single,", ".property("); | ||
|
||
return gremlin; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
90 changes: 90 additions & 0 deletions
90
hugegraph-api/src/main/java/com/baidu/hugegraph/api/gremlin/GremlinQueryAPI.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,90 @@ | ||
package com.baidu.hugegraph.api.gremlin; | ||
|
||
import java.util.Map; | ||
import java.util.Set; | ||
|
||
import com.baidu.hugegraph.api.API; | ||
import com.baidu.hugegraph.config.HugeConfig; | ||
import com.baidu.hugegraph.config.ServerOptions; | ||
import com.baidu.hugegraph.exception.HugeGremlinException; | ||
import com.google.common.collect.ImmutableMap; | ||
import com.google.common.collect.ImmutableSet; | ||
|
||
import javax.inject.Provider; | ||
import javax.ws.rs.core.Context; | ||
import javax.ws.rs.core.HttpHeaders; | ||
import javax.ws.rs.core.MediaType; | ||
import javax.ws.rs.core.Response; | ||
|
||
public class GremlinQueryAPI extends API { | ||
|
||
private static final Set<String> FORBIDDEN_REQUEST_EXCEPTIONS = | ||
ImmutableSet.of("java.lang.SecurityException", | ||
"jakarta.ws.rs.ForbiddenException"); | ||
private static final Set<String> BAD_REQUEST_EXCEPTIONS = ImmutableSet.of( | ||
"java.lang.IllegalArgumentException", | ||
"java.util.concurrent.TimeoutException", | ||
"groovy.lang.", | ||
"org.codehaus.", | ||
"com.baidu.hugegraph." | ||
); | ||
|
||
@Context | ||
private Provider<HugeConfig> configProvider; | ||
|
||
private GremlinClient client; | ||
|
||
public GremlinClient client() { | ||
if (this.client != null) { | ||
return this.client; | ||
} | ||
HugeConfig config = this.configProvider.get(); | ||
String url = config.get(ServerOptions.GREMLIN_SERVER_URL); | ||
int timeout = config.get(ServerOptions.GREMLIN_SERVER_TIMEOUT) * 1000; | ||
int maxRoutes = config.get(ServerOptions.GREMLIN_SERVER_MAX_ROUTE); | ||
this.client = new GremlinClient(url, timeout, maxRoutes, maxRoutes); | ||
return this.client; | ||
} | ||
|
||
protected static Response transformResponseIfNeeded(Response response) { | ||
MediaType mediaType = response.getMediaType(); | ||
if (mediaType != null) { | ||
// Append charset | ||
assert MediaType.APPLICATION_JSON_TYPE.equals(mediaType); | ||
response.getHeaders().putSingle(HttpHeaders.CONTENT_TYPE, | ||
mediaType.withCharset(CHARSET)); | ||
} | ||
|
||
Response.StatusType status = response.getStatusInfo(); | ||
if (status.getStatusCode() < 400) { | ||
// No need to transform if normal response without error | ||
return response; | ||
} | ||
|
||
if (mediaType == null || !JSON.equals(mediaType.getSubtype())) { | ||
String message = response.readEntity(String.class); | ||
throw new HugeGremlinException(status.getStatusCode(), | ||
ImmutableMap.of("message", message)); | ||
} | ||
|
||
@SuppressWarnings("unchecked") | ||
Map<String, Object> map = response.readEntity(Map.class); | ||
String exClassName = (String) map.get("Exception-Class"); | ||
if (FORBIDDEN_REQUEST_EXCEPTIONS.contains(exClassName)) { | ||
status = Response.Status.FORBIDDEN; | ||
} else if (matchBadRequestException(exClassName)) { | ||
status = Response.Status.BAD_REQUEST; | ||
} | ||
throw new HugeGremlinException(status.getStatusCode(), map); | ||
} | ||
|
||
private static boolean matchBadRequestException(String exClass) { | ||
if (exClass == null) { | ||
return false; | ||
} | ||
if (BAD_REQUEST_EXCEPTIONS.contains(exClass)) { | ||
return true; | ||
} | ||
return BAD_REQUEST_EXCEPTIONS.stream().anyMatch(exClass::startsWith); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
86 changes: 86 additions & 0 deletions
86
hugegraph-test/src/main/java/com/baidu/hugegraph/api/CypherApiTest.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,86 @@ | ||
/* | ||
* Copyright 2017 HugeGraph Authors | ||
* | ||
* 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 com.baidu.hugegraph.api; | ||
|
||
import static com.baidu.hugegraph.testutil.Assert.assertContains; | ||
|
||
import java.util.Map; | ||
|
||
import org.junit.Before; | ||
import org.junit.Test; | ||
|
||
import com.google.common.collect.ImmutableMap; | ||
|
||
import javax.ws.rs.core.Response; | ||
|
||
public class CypherApiTest extends BaseApiTest { | ||
|
||
private static final String PATH = URL_PREFIX + "/cypher"; | ||
private static final String QUERY = "MATCH (n:person) where n.city ='Beijing' return n"; | ||
private static final String QUERY_RESULT = "Beijing"; | ||
|
||
@Before | ||
public void prepareSchema() { | ||
BaseApiTest.initPropertyKey(); | ||
BaseApiTest.initVertexLabel(); | ||
BaseApiTest.initEdgeLabel(); | ||
BaseApiTest.initIndexLabel(); | ||
BaseApiTest.initVertex(); | ||
BaseApiTest.initEdge(); | ||
} | ||
|
||
@Test | ||
public void testGet() { | ||
Map<String, Object> params = ImmutableMap.of("cypher", QUERY); | ||
Response r = client().get(PATH, params); | ||
|
||
this.validStatusAndTextContains(QUERY_RESULT, r); | ||
} | ||
|
||
@Test | ||
public void testPost() { | ||
this.testCypherQueryAndContains(QUERY, QUERY_RESULT); | ||
} | ||
|
||
@Test | ||
public void testCreate() { | ||
this.testCypherQueryAndContains("CREATE (n:person { name : 'test', " + | ||
"age: 20, city: 'Hefei' }) return n", | ||
"Hefei"); | ||
} | ||
|
||
@Test | ||
public void testRelationQuery() { | ||
String cypher = "MATCH (n:person)-[r:knows]->(friend:person)\n" + | ||
"WHERE n.name = 'marko'\n" + | ||
"RETURN n, friend.name AS friend"; | ||
this.testCypherQueryAndContains(cypher, "friend"); | ||
} | ||
|
||
private void testCypherQueryAndContains(String cypher, String containsText) { | ||
Response r = client().post(PATH, cypher); | ||
this.validStatusAndTextContains(containsText, r); | ||
} | ||
|
||
private void validStatusAndTextContains(String value, Response r) { | ||
String content = assertResponseStatus(200, r); | ||
assertContains(value, content); | ||
} | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
add CypherApiTest into ApiTestSuite to run tests