Last active
June 20, 2017 23:29
-
-
Save bbhoss/43586fa718d210fa81b8e6b79101c6a9 to your computer and use it in GitHub Desktop.
Using Google Natural Language API from PL/Python. Make sure to set up authentication and install the proper libraries to the PL/Python PYTHONPATH first.
This file contains hidden or 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
CREATE EXTENSION plpython3u; | |
CREATE TYPE GOOGSENTIMENTRESULT AS ( | |
sentiment FLOAT, | |
magnitude FLOAT | |
); | |
CREATE OR REPLACE FUNCTION GOOGsentiment(txt TEXT) | |
RETURNS GOOGSENTIMENTRESULT | |
AS $$ | |
# Imports the Google Cloud client library | |
from google.cloud import language | |
# Instantiates a client | |
language_client = language.Client() | |
document = language_client.document_from_text(txt) | |
# Detects the sentiment of the text | |
sentiment = document.analyze_sentiment().sentiment | |
return { "sentiment": sentiment.score, "magnitude": sentiment.magnitude } | |
$$ LANGUAGE plpython3u; | |
-- Usage: | |
SELECT GOOGsentiment('hello there, friend! It sure is a great day, eh?'); | |
-- Example, use it directly with your data: | |
SELECT DISTINCT ON (response) GOOGsentiment(response), response | |
FROM your_table_with_responses | |
WHERE LENGTH(response) > 200 | |
ORDER BY response; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment