Skip to content

Instantly share code, notes, and snippets.

@bbhoss
Last active June 20, 2017 23:29
Show Gist options
  • Save bbhoss/43586fa718d210fa81b8e6b79101c6a9 to your computer and use it in GitHub Desktop.
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.
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