Skip to content

Commit 4704062

Browse files
author
Ghislain Fourny
committed
Support for pandas dataframes.
1 parent 000ff50 commit 4704062

5 files changed

Lines changed: 61 additions & 16 deletions

File tree

README.md

Lines changed: 30 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@ When passing Python values to JSONiq or getting them from a JSONiq queries, the
4646

4747
| Python | JSONiq |
4848
|-------|-------|
49+
|tuple|sequence of items|
4950
|dict|object|
5051
|list|array|
5152
|str|string|
@@ -73,6 +74,7 @@ You can directly copy paste the code below to a Python file and execute it with
7374

7475
```
7576
from jsoniq import RumbleSession
77+
import pandas as pd
7678
7779
# The syntax to start a session is similar to that of Spark.
7880
# A RumbleSession is a SparkSession that additionally knows about RumbleDB.
@@ -155,16 +157,16 @@ print(seq.json());
155157
###### Binding JSONiq variables to Python values ###########
156158
############################################################
157159
158-
# It is possible to bind a JSONiq variable to a list of native Python values
160+
# It is possible to bind a JSONiq variable to a tuple of native Python values
159161
# and then use it in a query.
160162
# JSONiq, variables are bound to sequences of items, just like the results of JSONiq
161163
# queries are sequence of items.
162-
# A Python list will be seamlessly converted to a sequence of items by the library.
164+
# A Python tuple will be seamlessly converted to a sequence of items by the library.
163165
# Currently we only support strs, ints, floats, booleans, None, lists, and dicts.
164166
# But if you need more (like date, bytes, etc) we will add them without any problem.
165167
# JSONiq has a rich type system.
166168
167-
rumble.bind('$c', [1,2,3,4, 5, 6])
169+
rumble.bind('$c', (1,2,3,4, 5, 6))
168170
print(rumble.jsoniq("""
169171
for $v in $c
170172
let $parity := $v mod 2
@@ -176,7 +178,7 @@ return { switch($parity)
176178
}
177179
""").json())
178180
179-
rumble.bind('$c', [[1,2,3],[4,5,6]])
181+
rumble.bind('$c', ([1,2,3],[4,5,6]))
180182
print(rumble.jsoniq("""
181183
for $i in $c
182184
return [
@@ -185,18 +187,34 @@ return [
185187
]
186188
""").json())
187189
188-
rumble.bind('$c', [{"foo":[1,2,3]},{"foo":[4,{"bar":[1,False, None]},6]}])
190+
rumble.bind('$c', ({"foo":[1,2,3]},{"foo":[4,{"bar":[1,False, None]},6]}))
189191
print(rumble.jsoniq('{ "results" : $c.foo[[2]] }').json())
190192
191-
# It is possible to bind only one value. The it must be provided as a singleton list.
193+
# It is possible to bind only one value. The it must be provided as a singleton tuple.
192194
# This is because in JSONiq, an item is the same a sequence of one item.
193-
rumble.bind('$c', [42])
195+
rumble.bind('$c', (42,))
194196
print(rumble.jsoniq('for $i in 1 to $c return $i*$i').json())
195197
196198
# For convenience and code readability, you can also use bindOne().
197199
rumble.bindOne('$c', 42)
198200
print(rumble.jsoniq('for $i in 1 to $c return $i*$i').json())
199201
202+
##########################################################
203+
##### Binding JSONiq variables to pandas DataFrames ######
204+
##### Getting the output as a Pandas DataFrame ######
205+
##########################################################
206+
207+
# Creating a dummy pandas dataframe
208+
data = {'Name': ['Alice', 'Bob', 'Charlie'],
209+
'Age': [30,25,35]};
210+
pdf = pd.DataFrame(data);
211+
212+
# Binding a pandas dataframe
213+
rumble.bind('$a',pdf);
214+
seq = rumble.jsoniq('$a.Name')
215+
# Getting the output as a pandas dataframe
216+
print(seq.pdf())
217+
200218
201219
################################################
202220
##### Using Pyspark DataFrames with JSONiq #####
@@ -324,6 +342,11 @@ Even more queries can be found [here](https://colab.research.google.com/github/R
324342

325343
# Last updates
326344

345+
## Version 0.1.0 alpha 13
346+
- Allow to bind JSONiq variables to pandas dataframes
347+
- Allow to retrieve the output of a JSONiq query as a pandas dataframes (if the output is available as a dataframe, i.e., availableOutputs() returns a list that contains "DataFrame")
348+
- Clean up the mapping to strictly map tuples to sequence of items, and lists ot array items. This will avoid confusion between arrays and sequences.
349+
327350
## Version 0.1.0 alpha 12
328351
- Allow to bind JSONiq variables to Python values (mapping Python lists to sequences of items). This makes it possible to manipulate Python values directly with JSONiq and even without any knowledge of Spark at all.
329352
- renamed bindDataFrameAsVariable() to bind(), which can be used both with DataFrames and Python lists.

pyproject.toml

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,8 @@ version = "0.1.0a12"
88
description = "Python edition of RumbleDB, a JSONiq engine"
99
requires-python = ">=3.11"
1010
dependencies = [
11-
"pyspark==4.0"
11+
"pyspark==4.0",
12+
"pandas==2.3"
1213
]
1314
authors = [
1415
{name = "Ghislain Fourny", email = "ghislain.fourny@inf.ethz.ch"},
@@ -23,6 +24,8 @@ classifiers = [
2324
"Programming Language :: Python :: 3.11",
2425
"Programming Language :: Python :: 3.12",
2526
"Programming Language :: Python :: 3.13",
27+
"Typing :: Typed",
28+
"License :: OSI Approved :: Apache Software License"
2629
]
2730

2831
[tool.setuptools.packages.find]

requirements.txt

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,2 @@
1-
pyspark==4.0.0
1+
pyspark==4.0
2+
pandas==2.3

src/jsoniq/sequence.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ def __init__(self, sequence, sparksession):
1010
self._sparksession = sparksession
1111

1212
def json(self):
13-
return [json.loads(l.serializeAsJSON()) for l in self._jsequence.items()]
13+
return tuple([json.loads(l.serializeAsJSON()) for l in self._jsequence.items()])
1414

1515
def rdd(self):
1616
rdd = self._jsequence.getAsPickledStringRDD();
@@ -20,6 +20,9 @@ def rdd(self):
2020
def df(self):
2121
return DataFrame(self._jsequence.getAsDataFrame(), self._sparksession)
2222

23+
def pdf(self):
24+
return self.df().toPandas()
25+
2326
def nextJSON(self):
2427
return self._jsequence.next().serializeAsJSON()
2528

src/jsoniq/session.py

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import platform
55
import os
66
import re
7+
import pandas as pd
78
import importlib.resources as pkg_resources
89

910
with pkg_resources.path("jsoniq.jars", "rumbledb-1.24.0.jar") as jar_path:
@@ -84,6 +85,8 @@ def __getattr__(self, name):
8485
_builder = Builder()
8586

8687
def convert(self, value):
88+
if isinstance(value, tuple):
89+
return [ self.convert(v) for v in value]
8790
if isinstance(value, bool):
8891
return self._sparksession._jvm.org.rumbledb.items.ItemFactory.getInstance().createBooleanItem(value)
8992
elif isinstance(value, str):
@@ -114,18 +117,30 @@ def bind(self, name: str, valueToBind):
114117
if not name.startswith("$"):
115118
raise ValueError("Variable name must start with a dollar symbol ('$').")
116119
name = name[1:]
117-
if isinstance(valueToBind, list):
118-
items = [ self.convert(value) for value in valueToBind]
119-
conf.setExternalVariableValue(name, items)
120-
return self
121-
if(hasattr(valueToBind, "_get_object_id")):
120+
if isinstance(valueToBind, SequenceOfItems):
121+
outputs = valueToBind.availableOutputs()
122+
if isinstance(outputs, list) and "DataFrame" in outputs:
123+
conf.setExternalVariableValue(name, valueToBind.df());
124+
# TODO support binding a variable to an RDD
125+
#elif isinstance(outputs, list) and "RDD" in outputs:
126+
# conf.setExternalVariableValue(name, valueToBind.getAsRDD());
127+
else:
128+
conf.setExternalVariableValue(name, valueToBind.items());
129+
elif isinstance(valueToBind, pd.DataFrame):
130+
pysparkdf = self._sparksession.createDataFrame(valueToBind)
131+
conf.setExternalVariableValue(name, pysparkdf._jdf);
132+
elif isinstance(valueToBind, tuple):
133+
conf.setExternalVariableValue(name, self.convert(valueToBind))
134+
elif isinstance(valueToBind, list):
135+
raise ValueError("To avoid confusion, a sequence of items must be provided as a Python tuple, not as a Python list. Lists are mapped to single array items, while tuples are mapped to sequences of items. If you want to bind the variable to one array item, then you need to wrap the provided list inside a singleton tuple and try again, or you can also call bindOne() instead.")
136+
elif(hasattr(valueToBind, "_get_object_id")):
122137
conf.setExternalVariableValue(name, valueToBind);
123138
else:
124139
conf.setExternalVariableValue(name, valueToBind._jdf);
125140
return self;
126141

127142
def bindOne(self, name: str, value):
128-
return self.bind(name, [value])
143+
return self.bind(name, (value,))
129144

130145
def bindDataFrameAsVariable(self, name: str, df):
131146
conf = self._jrumblesession.getConfiguration();

0 commit comments

Comments
 (0)