Skip to content
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

GraphQL support #443

Merged
merged 1 commit into from
Oct 15, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions packages/vaex-graphql/LICENSE.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2015, Maarten A. Breddels

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
1 change: 1 addition & 0 deletions packages/vaex-graphql/MANIFEST.in
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
include LICENSE.txt
31 changes: 31 additions & 0 deletions packages/vaex-graphql/setup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import os
import imp
from setuptools import setup

dirname = os.path.dirname(__file__)
path_version = os.path.join(dirname, 'vaex/graphql/_version.py')
version = imp.load_source('version', path_version)

name = 'vaex'
author = 'Maarten A. Breddels'
author_email= '[email protected]'
license = 'MIT'
version = version.__version__
url = 'https://www.github.com/vaexio/vaex'
install_requires_astro = ['vaex-core>=1.0.0,<2']

setup(
name=name + '-graphql',
version=version,
description='GraphQL support for accessing vaex DataFrame',
url=url,
author=author,
author_email=author_email,
install_requires=install_requires_astro,
license=license,
packages=['vaex.graphql'],
zip_safe=False,
entry_points={
'vaex.dataframe.accessor': ['graphql = vaex.graphql:DataFrameAccessorGraphQL'],
},
)
249 changes: 249 additions & 0 deletions packages/vaex-graphql/vaex/graphql/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,249 @@
import graphene
import graphql.execution
import vaex

if graphene.VERSION >= (3, 0):
class ExecutionContext(graphql.execution.ExecutionContext):
def __init__(self, *args, **kwargs):
self.call_stack_count = 0
super().__init__(*args, **kwargs)

def execute_fields(
self,
parent_type,
source_value,
path,
fields,
):
try:
self.call_stack_count += 1
result = super().execute_fields(parent_type, source_value, path, fields)
finally:
self.call_stack_count -= 1
if self.call_stack_count == 0:
for df in self.context_value['dataframes']:
df.execute()
return result
else:
ExecutionContext = None


class DataFrameAccessorGraphQL(object):
def __init__(self, df):
self.df = df

def query(self, name='df'):
"""Creates a graphene query object exposing this dataframe named `name`"""
return create_query({name: self.df})

def schema(self, name='df', auto_camelcase=False, **kwargs):
return graphene.Schema(query=self.query(name), auto_camelcase=auto_camelcase, **kwargs)

def execute(self, *args, **kwargs):
if ExecutionContext:
if 'execution_context_class' not in kwargs:
kwargs['execution_context_class'] = ExecutionContext
assert 'context_value' not in kwargs
kwargs['context_value'] = {'dataframes': [self.df]}
return self.schema().execute(*args, **kwargs)

def serve(self, port=9001, address='', name='df', verbose=True):
from .tornado import Application
schema = self.schema(name=name)
app = Application(schema)
app.listen(port, address)
if not address:
address = 'localhost'
if verbose:
print(f'serving at: http://{address}:{port}/graphql')


def map_to_field(df, name):
dtype = df[name].dtype
if dtype == str:
return graphene.String
elif dtype.kind == "f":
return graphene.Float
elif dtype.kind == "i":
return graphene.Int
elif dtype.kind == "b":
return graphene.Boolean
elif dtype.kind == "M":
return graphene.DateTime
elif dtype.kind == "m":
return graphene.DateTime # TODO, not sure how we're gonna deal with timedelta
else:
raise ValueError('dtype not supported: %r' % dtype)

def create_aggregation_on_field(df, groupby):
postfix = "_".join(groupby)
if postfix:
postfix = "_" + postfix
class AggregationOnFieldBase(graphene.ObjectType):
def __init__(self, df, agg, groupby):
self.df = df
self.agg = agg
self.groupby = groupby
class Meta:
def default_resolver(name, __, obj, info):
if obj.groupby:
groupby = obj.df.groupby(obj.groupby)
agg = getattr(vaex.agg, obj.agg)(name)
dfg = groupby.agg({'agg': agg})
agg_values = dfg['agg']
return agg_values.tolist()
return getattr(obj.df, obj.agg)(name)
if groupby:
attrs = {name: graphene.List(map_to_field(df, name)) for name in df.get_column_names()}
else:
attrs = {name: map_to_field(df, name)() for name in df.get_column_names()}
attrs['Meta'] = Meta
DataFrameAggregationOnField = type("AggregationOnField"+postfix, (AggregationOnFieldBase, ), attrs)
return DataFrameAggregationOnField

# def create_groupedby(df, groupby):
# postfix = "_".join(groupby)
# if postfix:
# posfix = "_" + postfix
# class AggregationOnFieldBase(graphene.ObjectType):
# def __init__(self, df, agg, groupby):
# self.df = df
# self.agg = agg
# self.groupby = groupby
# class Meta:
# def default_resolver(name, __, obj, info):
# return getattr(obj.df, obj.agg)(name)
# attrs = {name: map_to_field(df, name) for name in df.get_column_names()}
# attrs['Meta'] = Meta
# DataFrameAggregationOnField = type("AggregationOnField"+postfix, (AggregationOnFieldBase, ), attrs)
# return DataFrameAggregationOnField

def create_groupby(df, groupby):
postfix = "_".join(groupby)
if postfix:
postfix = "_" + postfix
class GroupByBase(graphene.ObjectType):
count = graphene.List(graphene.Int)
keys = graphene.List(graphene.Int)

def __init__(self, df, by=None):
self.df = df
self.by = [] if by is None else by
self._groupby = None # cached lazy object
super(GroupByBase, self).__init__()

@property
def groupby(self):
if self._groupby is None:
self._groupby = self.df.groupby(self.by)
return self._groupby

def resolve_count(self, info):
dfg = self.groupby.agg('count')
return dfg['count'].tolist()

def resolve_keys(self, info):
return self.groupby.coords1d[-1]

# class Meta:
# def default_resolver(name, __, obj, info):
# return getattr(obj.df, obj.agg)(name)
def field_groupby(name):
Aggregate = create_aggregate(df, groupby + [name])
def resolver(*args, **kwargs):
return Aggregate(df, groupby + [name])
return graphene.Field(Aggregate, resolver=resolver)
attrs = {name: field_groupby(name) for name in df.get_column_names()}
# attrs['Meta'] = Meta
GroupBy = type("GroupBy"+postfix, (GroupByBase, ), attrs)
return GroupBy

def create_aggregate(df, groupby=None):
postfix = "_".join(groupby)
if postfix:
postfix = "_" + postfix
if groupby is None: groupby = []

AggregationOnField = create_aggregation_on_field(df, groupby)
if len(groupby):
# CountType = graphene.Int
CountType = graphene.List(graphene.Int)

else:
CountType = graphene.Int()
# for i in range(len(groupby)):
# CountType = graphene.List(CountType)


class AggregationBase(graphene.ObjectType):
count = CountType
min = graphene.Field(AggregationOnField)
max = graphene.Field(AggregationOnField)
mean = graphene.Field(AggregationOnField)

hello = graphene.String(description='A typical hello world')
def resolve_hello(self, info):
return 'World'

def __init__(self, df, by=None):
self.df = df
self.by = [] if by is None else by
assert self.by == groupby
self._groupby = None # cached lazy object
super(AggregationBase, self).__init__()

@property
def groupby_object(self):
if self._groupby is None:
self._groupby = self.df.groupby(self.by)
return self._groupby

def resolve_count(self, info):
if self.by:
groupby = self.groupby_object
dfg = self.groupby_object.agg('count')
counts = dfg['count']
return counts.tolist()
return len(self.df)
def resolve_min(self, info):
return AggregationOnField(self.df, 'min', self.by)
def resolve_max(self, info):
return AggregationOnField(self.df, 'max', self.by)
def resolve_mean(self, info):
return AggregationOnField(self.df, 'mean', self.by)

# fields_agg = {name: graphene.Field(DataFrameAggregationField) for name in df.get_column_names()}
attrs = {}
if len(groupby) < 2:
GroupBy = create_groupby(df, groupby)
def resolver(*args, **kwargs):
return GroupBy(df, groupby)
attrs["groupby"] = graphene.Field(GroupBy, resolver=resolver, description="GroupBy a field for %s" % '...')

Aggregation = type("Aggregation"+postfix, (AggregationBase, ), attrs)
return Aggregation

def create_query(dfs):
class QueryBase(graphene.ObjectType):
hello = graphene.String(description='A typical hello world')
fields = {}
for name, df in dfs.items():
columns = df.get_column_names()
columns = [k for k in columns if df[k].dtype == str or df[k].dtype.kind != 'O']
df = df[columns]
Aggregate = create_aggregate(df, [])
def closure(df=df, name=name, Aggregate=Aggregate):
def resolve(*args, **kwargs):
return Aggregate(df=df)
return resolve
fields[name] = graphene.Field(Aggregate, resolver=closure(), description="Aggregations for %s" % name)

# GroupBy = create_groupby(df, [])
# def closure(df=df, name=name, GroupBy=GroupBy):
# def resolve(*args, **kwargs):
# return GroupBy(df=df)
# return resolve
# fields[name+"_groupby"] = graphene.Field(GroupBy, resolver=closure(), description="GroupBy a field for %s" % name)
return type("Query", (QueryBase, ), fields)
# schema = graphene.Schema(query=create_query({'taxi': df}), auto_camelcase=False)
# schema
7 changes: 7 additions & 0 deletions packages/vaex-graphql/vaex/graphql/__main__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import sys
import vaex
from tornado.ioloop import IOLoop

df = vaex.open(sys.argv[1])
df.graphql.serve()
IOLoop.instance().start()
2 changes: 2 additions & 0 deletions packages/vaex-graphql/vaex/graphql/_version.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
__version_tuple__ = (0, 0, 1)
__version__ = '0.0.1'
23 changes: 23 additions & 0 deletions packages/vaex-graphql/vaex/graphql/tornado.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import tornado.web
from tornado.ioloop import IOLoop

from graphene_tornado.schema import schema
from graphene_tornado.tornado_graphql_handler import TornadoGraphQLHandler


class Application(tornado.web.Application):

def __init__(self, schema):
handlers = [
(r'/graphql', TornadoGraphQLHandler, dict(graphiql=True, schema=schema)),
(r'/graphql/batch', TornadoGraphQLHandler, dict(graphiql=True, schema=schema, batch=True)),
(r'/graphql/graphiql', TornadoGraphQLHandler, dict(graphiql=True, schema=schema))
]
tornado.web.Application.__init__(self, handlers)


if __name__ == '__main__':
app = ExampleApplication()
app.listen(5000)
IOLoop.instance().start()