Skip to content

Commit 1c11d3a

Browse files
wey-guBeautyyuYanli
andcommitted
feat: cast params (#349)
* feat: cast params #273 * handle None of params * lint: make black happy * docs and example added with UT coverage * docs of result set as primitive * fix structure to make the cast non-breaking (#350) * make linter happy * minor fix * remove list cast * fix NList usage * fix test * chore: polish readme --------- Co-authored-by: 盐粒 Yanli <[email protected]>
1 parent 519c376 commit 1c11d3a

File tree

5 files changed

+294
-79
lines changed

5 files changed

+294
-79
lines changed

README.md

+49
Original file line numberDiff line numberDiff line change
@@ -16,12 +16,16 @@
1616

1717
- If you're building Graph Analysis Tools(Scan instead of Query), you may want to use the **Storage Client** to scan vertices and edges, see [Quick Example: Using Storage Client to Scan Vertices and Edges](#Quick-Example:-Using-Storage-Client-to-Scan-Vertices-and-Edges).
1818

19+
- For parameterized query, see [Example: Server-Side Evaluated Parameters](#Example:-Server-Side-Evaluated-Parameters).
20+
1921
### Handling Query Results
2022

2123
- On how to form a query result into a **Pandas DataFrame**, see [Example: Fetching Query Results into a Pandas DataFrame](#Example:-Fetching-Query-Results-into-a-Pandas-DataFrame).
2224

2325
- On how to render/visualize the query result, see [Example: Extracting Edge and Vertex Lists from Query Results](#Example:-Extracting-Edge-and-Vertex-Lists-from-Query-Results), it demonstrates how to extract lists of edges and vertices from any query result by utilizing the `ResultSet.dict_for_vis()` method.
2426

27+
- On how to get rows of dict/JSON structure with primitive types, see [Example: Retrieve Primitive Typed Results](#Example:-Retrieve-Primitive-Typed-Results).
28+
2529
### Jupyter Notebook Integration
2630

2731
[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/wey-gu/jupyter_nebulagraph/blob/main/docs/get_started.ipynb)
@@ -119,6 +123,34 @@ Session Pool comes with the following assumptions:
119123

120124
For more details, see [SessionPoolExample.py](example/SessionPoolExample.py).
121125

126+
## Example: Server-Side Evaluated Parameters
127+
128+
To enable parameterization of the query, refer to the following example:
129+
130+
> Note: Not all tokens of a query can be parameterized. You can quickly verify it via iPython or Nebula-Console in an interactive way.
131+
132+
```python
133+
params = {
134+
"p1": 3,
135+
"p2": True,
136+
"p3": "Bob",
137+
"ids": ["player100", "player101"], # second query
138+
}
139+
140+
result = client.execute_py_params(
141+
"RETURN abs($p1)+3 AS col1, (toBoolean($p2) AND false) AS col2, toLower($p3)+1 AS col3",
142+
params,
143+
)
144+
145+
result = client.execute_py_params(
146+
"MATCH (v) WHERE id(v) in $ids RETURN id(v) AS vertex_id",
147+
params,
148+
)
149+
```
150+
151+
For further information, consult [Params.py](example/Params.py).
152+
153+
122154
## Example: Extracting Edge and Vertex Lists from Query Results
123155

124156
For graph visualization purposes, the following code snippet demonstrates how to effortlessly extract lists of edges and vertices from any query result by utilizing the `ResultSet.dict_for_vis()` method.
@@ -206,6 +238,23 @@ The dict/JSON structure with `dict_for_vis()` is as follows:
206238

207239
</details>
208240

241+
## Example: Retrieve Primitive Typed Results
242+
243+
The executed result is typed as `ResultSet`, and you can inspect its structure using `dir()`.
244+
245+
For each data cell in the `ResultSet`, you can use `.cast()` to retrieve raw wrapped data (with sugar) such as a Vertex (Node), Edge (Relationship), Path, Value (Int, Float, etc.). Alternatively, you can use `.cast_primitive()` to obtain values in primitive types like dict, int, or float, depending on your needs.
246+
247+
For more details, refer to [FromResp.py](example/FromResp.py).
248+
249+
Additionally, `ResultSet.as_primitive()` provides a convenient method to convert the result set into a list of dictionaries (similar to JSONL format) containing primitive values for each row.
250+
251+
```python
252+
result = session.execute('<your query>')
253+
254+
result_dict = result.as_primitive()
255+
print(result_dict)
256+
```
257+
209258
## Example: Fetching Query Results into a Pandas DataFrame
210259

211260
> For `nebula3-python>=3.6.0`:

example/Params.py

+62
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
import time
2+
3+
from nebula3.gclient.net import ConnectionPool
4+
from nebula3.Config import Config
5+
from nebula3.common import ttypes
6+
7+
# define a config
8+
config = Config()
9+
connection_pool = ConnectionPool()
10+
connection_pool.init([("127.0.0.1", 9669)], config)
11+
12+
# get session from the connection pool
13+
client = connection_pool.get_session("root", "nebula")
14+
client.execute("CREATE SPACE IF NOT EXISTS test(vid_type=FIXED_STRING(30));")
15+
16+
17+
time.sleep(
18+
6
19+
) # two cycles of heartbeat, by default of a NebulaGraph cluster, we will need to sleep 20s
20+
21+
client.execute(
22+
"USE test;"
23+
"CREATE TAG IF NOT EXISTS person(name string, age int);"
24+
"CREATE EDGE IF NOT EXISTS like (likeness double);"
25+
)
26+
27+
# prepare NebulaGraph Byte typed parameters
28+
29+
bval = ttypes.Value()
30+
bval.set_bVal(True)
31+
ival = ttypes.Value()
32+
ival.set_iVal(3)
33+
sval = ttypes.Value()
34+
sval.set_sVal("Bob")
35+
36+
params = {"p1": ival, "p2": bval, "p3": sval}
37+
38+
39+
# we could pass NebulaGraph Raw byte params like params, they will be evaluated in server side:
40+
resp = client.execute_parameter(
41+
"RETURN abs($p1)+3 AS col1, (toBoolean($p2) AND false) AS col2, toLower($p3)+1 AS col3",
42+
params,
43+
)
44+
45+
# It may be not dev friendly to prepare i.e. a list of string typed params, actually NebulaGrap python client supports to pass premitive typed parms, too.
46+
47+
params_premitive = {
48+
"p1": 3,
49+
"p2": True,
50+
"p3": "Bob",
51+
"p4": ["Bob", "Lily"],
52+
}
53+
54+
resp = client.execute_py_params(
55+
"RETURN abs($p1)+3 AS col1, (toBoolean($p2) and false) AS col2, toLower($p3)+1 AS col3",
56+
params_premitive,
57+
)
58+
59+
resp = client.execute_py_params(
60+
"MATCH (v) WHERE id(v) in $p4 RETURN id(v) AS vertex_id",
61+
params_premitive,
62+
)
File renamed without changes.

nebula3/gclient/net/base.py

+72
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
1+
import datetime
12
from abc import abstractmethod
23
from typing import Dict, Any, Optional
34
from nebula3.data.ResultSet import ResultSet
5+
from nebula3.common.ttypes import ErrorCode, Value, NList, Date, Time, DateTime
46

57

68
class BaseExecutor:
@@ -21,3 +23,73 @@ def execute(self, stmt: str) -> ResultSet:
2123

2224
def execute_json(self, stmt: str) -> bytes:
2325
return self.execute_json_with_parameter(stmt, None)
26+
27+
def execute_py_params(
28+
self, stmt: str, params: Optional[Dict[str, Any]]
29+
) -> ResultSet:
30+
"""**Recommended** Execute a statement with parameters in Python type instead of thrift type."""
31+
return self.execute_parameter(stmt, _build_byte_param(params))
32+
33+
34+
def _build_byte_param(params: dict) -> dict:
35+
byte_params = {}
36+
for k, v in params.items():
37+
if isinstance(v, Value):
38+
byte_params[k] = v
39+
elif str(type(v)).startswith("nebula3.common.ttypes"):
40+
byte_params[k] = v
41+
else:
42+
byte_params[k] = _cast_value(v)
43+
return byte_params
44+
45+
46+
def _cast_value(value: Any) -> Value:
47+
"""
48+
Cast the value to nebula Value type
49+
ref: https://github.com/vesoft-inc/nebula/blob/master/src/common/datatypes/Value.cpp
50+
:param value: the value to be casted
51+
:return: the casted value
52+
"""
53+
casted_value = Value()
54+
if isinstance(value, bool):
55+
casted_value.set_bVal(value)
56+
elif isinstance(value, int):
57+
casted_value.set_iVal(value)
58+
elif isinstance(value, str):
59+
casted_value.set_sVal(value)
60+
elif isinstance(value, float):
61+
casted_value.set_fVal(value)
62+
elif isinstance(value, datetime.date):
63+
date_value = Date(year=value.year, month=value.month, day=value.day)
64+
casted_value.set_dVal(date_value)
65+
elif isinstance(value, datetime.time):
66+
time_value = Time(
67+
hour=value.hour,
68+
minute=value.minute,
69+
sec=value.second,
70+
microsec=value.microsecond,
71+
)
72+
casted_value.set_tVal(time_value)
73+
elif isinstance(value, datetime.datetime):
74+
datetime_value = DateTime(
75+
year=value.year,
76+
month=value.month,
77+
day=value.day,
78+
hour=value.hour,
79+
minute=value.minute,
80+
sec=value.second,
81+
microsec=value.microsecond,
82+
)
83+
casted_value.set_dtVal(datetime_value)
84+
# TODO: add support for GeoSpatial
85+
elif isinstance(value, list):
86+
byte_list = []
87+
for item in value:
88+
byte_list.append(_cast_value(item))
89+
casted_value.set_lVal(NList(values=byte_list))
90+
elif isinstance(value, dict):
91+
# TODO: add support for NMap
92+
raise TypeError("Unsupported type: dict")
93+
else:
94+
raise TypeError(f"Unsupported type: {type(value)}")
95+
return casted_value

0 commit comments

Comments
 (0)