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鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: convert StreamedResultSet to Pandas Dataframe #226

Open
wants to merge 20 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -349,6 +349,7 @@
"google-auth": ("https://google-auth.readthedocs.io/en/stable", None),
"google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None,),
"grpc": ("https://grpc.io/grpc/python/", None),
"pandas": ("https://pandas.pydata.org/pandas-docs/stable/", None),
}


Expand Down
69 changes: 69 additions & 0 deletions google/cloud/spanner_v1/_pandas_helpers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
# Copyright 2021 Google LLC

# Licensed 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

# https://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.

import logging
Hardikr23 marked this conversation as resolved.
Show resolved Hide resolved
import warnings

SPANNER_TO_PANDAS_DTYPES = {
"INT64": "int64",
"STRING": "object",
"BOOL": "bool",
"BYTES": "object",
"ARRAY": "object",
"DATE": "datetime64[ns]",
"FLOAT64": "float64",
"NUMERIC": "object",
"TIMESTAMP": "datetime64[ns]",
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's remove this whole set of dtype conversion logic. It's error prone and the pandas defaults arguably get most things right.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we do want to keep this, then it should only include the "nullsafe" dtypes defined here: https://github.com/pydata/pandas-gbq/blob/22a6064ee616fbdd14ce2c8bf8bfe1ed7d3b6291/pandas_gbq/gbq.py#L644-L684

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Basically just float and datetimes

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done



def pd_dataframe(response_obj):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

response_obj is a very generic name that doesn't reflect the type. Please rename to something that indicates this is a StreamedResultSet. For example result_set

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

changed to result_set

"""This functions converts the query results into pandas dataframe

larkee marked this conversation as resolved.
Show resolved Hide resolved
:rtype: pandas.Dataframe
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
:rtype: pandas.Dataframe
:rtype: pandas.DataFrame

:returns: Dataframe with the help of a mapping dictionary which maps every spanner datatype to a pandas compatible datatype.
"""
try:
from pandas import DataFrame
except ImportError as err:
raise ImportError(
"Pandas module not found. It is needed for converting query result to Dataframe.\n Try running 'pip3 install pandas'"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
"Pandas module not found. It is needed for converting query result to Dataframe.\n Try running 'pip3 install pandas'"
"Pandas module not found. It is needed for converting query result to DataFrame.\n Try running 'pip3 install pandas'"

) from err

data = []
for row in response_obj:
data.append(row)
Hardikr23 marked this conversation as resolved.
Show resolved Hide resolved

columns_dict = {}
try:
for item in response_obj.fields:
columns_dict[item.name] = item.type_.code
except:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Don't catch all exceptions. What kinds of errors are you trying to handle? Let's be explicit.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i think this try catch is not needed now

logging.warning("Not able to create spanner to pandas fields mapping")
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is a warning really the most appropriate thing for this code path? As a user I wouldn't want to be surprised with lost data columns.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

removed this as we no longer have the dictionary for mapping as per below comments


# Creating list of columns to be mapped with the data
column_list = [k for k, v in columns_dict.items()]
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is can also be simplified

Suggested change
column_list = [k for k, v in columns_dict.items()]
column_list = list(columns_dict.keys())

That said, I don't think this is what we want. If we want to preserve column order in all Python versions, we need to create a list while we are iterating through fields.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Modified as per suggestion


# Creating dataframe using column headers and list of data rows
df = DataFrame(data, columns=column_list)

for k, v in columns_dict.items():
try:
df[k] = df[k].astype(SPANNER_TO_PANDAS_DTYPES[v.name])
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This will fail for a great number of the data types that you have defined. Many of these data types do not support nullable values.

Specifically int64 is going to give you trouble with NULLs.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removed the mapping dictionary and this step too

if v.name == "TIMESTAMP" or v.name == "DATE":
df[k] = df[k].dt.tz_localize("UTC")
except KeyError:
warnings.warn("Spanner Datatype not present in datatype mapping dictionary")
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please write the data type in the error / warning message.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

On second-thought, we don't really need this warning as the default of object type is likely desired anyway.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

removed the additional step where we were setting to pandas datatypes. Just kept additional check for datetime aware columns.


return df
14 changes: 14 additions & 0 deletions google/cloud/spanner_v1/streamed.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@

# pylint: disable=ungrouped-imports
from google.cloud.spanner_v1._helpers import _parse_value
from google.cloud.spanner_v1._pandas_helpers import pd_dataframe

# pylint: enable=ungrouped-imports

Expand Down Expand Up @@ -143,6 +144,19 @@ def __iter__(self):
while iter_rows:
yield iter_rows.pop(0)

def to_dataframe(self):
"""Returns the response in a pandas dataframe of the StreamedResultSet object
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's indicate "all rows" to be clear that this will download all data at once.

Suggested change
"""Returns the response in a pandas dataframe of the StreamedResultSet object
"""Creates a pandas DataFrame of all rows in the result set


:param: The response of type StreamedResultSet received from spanner api.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re: :param: The response of type StreamedResultSet received from spanner api.

In general, we don't document "self". When I mentioned the need to document this type, it was for the _pandas_helpers.pd_dataframe method.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Got it. Removed it for self.


:rtype: pandas.DataFrame

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

:returns: Dataframe created from the StreamedResultSet response object returned by execute_sql() method
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The context of this docstring is in the StreamedResultSet class, so we don't have to repeat tha6t.

Suggested change
:returns: Dataframe created from the StreamedResultSet response object returned by execute_sql() method
:returns: DataFrame created from the result set

"""
response_obj = self
df = pd_dataframe(response_obj)
return df

def one(self):
"""Return exactly one result, or raise an exception.

Expand Down
3 changes: 2 additions & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,8 @@
"opentelemetry-api==0.11b0",
"opentelemetry-sdk==0.11b0",
"opentelemetry-instrumentation==0.11b0",
]
],
"pandas": ["pandas >= 0.25.3"],
}


Expand Down
49 changes: 49 additions & 0 deletions tests/system/test_system_pandasDf.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# Copyright 2021 Google Inc.
Hardikr23 marked this conversation as resolved.
Show resolved Hide resolved
#
# Licensed 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.

from google.cloud import spanner_v1_mod
from google.auth.credentials import AnonymousCredentials
import pytest

# for referrence
TABLE_NAME = "testTable"
COLUMNS = ["id", "name"]
VALUES = [[1, "Alice"], [2, "Bob"]]
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We need a test with all available data types.

Also, we need tests that include null values in each of the data types.

  1. No nulls
  2. One or more nulls
  3. All nulls

I suspect we may need to cast to the appropriate dtype for TIMESTAMP and DATE columns in case (3) all nulls.



@pytest.fixture
def snapshot_obj():
try:
spanner_client = spanner_v1_mod.Client(
project="test-project",
client_options={"api_endpoint": "0.0.0.0:9010"},
credentials=AnonymousCredentials(),
)
instance_id = "test-instance"
instance = spanner_client.instance(instance_id)
database_id = "test-database"
database = instance.database(database_id)
with database.snapshot() as snapshot:
return snapshot

except:
pytest.skip("Cloud Spanner Emulator configuration is incorrect")

@pytest.mark.parametrize(("limit"), [(0), (1), (2)])
def test_df(limit, snapshot_obj):
results = snapshot_obj.execute_sql(
"Select * from testTable limit {limit}".format(limit=limit)
)
df = results.to_dataframe()
assert len(df) == limit
121 changes: 121 additions & 0 deletions tests/unit/test__pandas_helpers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
# Copyright 2016 Google LLC All rights reserved.
Hardikr23 marked this conversation as resolved.
Show resolved Hide resolved
#
# Licensed 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.


import unittest


class TestPandasDataFrame(unittest.TestCase):
def _getTargetClass(self):
from google.cloud.spanner_v1.streamed import StreamedResultSet

return StreamedResultSet

def _make_one(self, *args, **kwargs):
return self._getTargetClass()(*args, **kwargs)

@staticmethod
def _make_scalar_field(name, type_):
from google.cloud.spanner_v1 import StructType
from google.cloud.spanner_v1 import Type

return StructType.Field(name=name, type_=Type(code=type_))

@staticmethod
def _make_value(value):
from google.cloud.spanner_v1._helpers import _make_value_pb

return _make_value_pb(value)

@staticmethod
def _make_result_set_metadata(fields=(), transaction_id=None):
from google.cloud.spanner_v1 import ResultSetMetadata
from google.cloud.spanner_v1 import StructType

metadata = ResultSetMetadata(row_type=StructType(fields=[]))
for field in fields:
metadata.row_type.fields.append(field)
if transaction_id is not None:
metadata.transaction.id = transaction_id
return metadata

@staticmethod
def _make_result_set_stats(query_plan=None, **kw):
from google.cloud.spanner_v1 import ResultSetStats
from google.protobuf.struct_pb2 import Struct
from google.cloud.spanner_v1._helpers import _make_value_pb

query_stats = Struct(
fields={key: _make_value_pb(value) for key, value in kw.items()}
)
return ResultSetStats(query_plan=query_plan, query_stats=query_stats)

def test_multiple_rows(self):
from google.cloud.spanner_v1 import TypeCode

iterator = _MockCancellableIterator()
streamed = self._make_one(iterator)
FIELDS = [
self._make_scalar_field("Name", TypeCode.STRING),
self._make_scalar_field("Age", TypeCode.INT64),
]
metadata = streamed._metadata = self._make_result_set_metadata(FIELDS)
stats = streamed._stats = self._make_result_set_stats()
streamed._rows[:] = [["Alice", 1], ["Bob", 2], ["Adam", 3]]
df_obj = streamed.to_dataframe()
assert len(df_obj) == 3

def test_single_rows(self):
from google.cloud.spanner_v1 import TypeCode

iterator = _MockCancellableIterator()
streamed = self._make_one(iterator)
FIELDS = [
self._make_scalar_field("Name", TypeCode.STRING),
self._make_scalar_field("Age", TypeCode.INT64),
]
metadata = streamed._metadata = self._make_result_set_metadata(FIELDS)
stats = streamed._stats = self._make_result_set_stats()
streamed._rows[:] = [["Alice", 1]]
df_obj = streamed.to_dataframe()
assert len(df_obj) == 1

def test_no_rows(self):
from google.cloud.spanner_v1 import TypeCode

iterator = _MockCancellableIterator()
streamed = self._make_one(iterator)
FIELDS = [
self._make_scalar_field("Name", TypeCode.STRING),
self._make_scalar_field("Age", TypeCode.INT64),
]
metadata = streamed._metadata = self._make_result_set_metadata(FIELDS)
stats = streamed._stats = self._make_result_set_stats()
streamed._rows[:] = []
df_obj = streamed.to_dataframe()
assert len(df_obj) == 0


class _MockCancellableIterator(object):

cancel_calls = 0

def __init__(self, *values):
self.iter_values = iter(values)

def next(self):
return next(self.iter_values)

def __next__(self): # pragma: NO COVER Py3k
return self.next()