Quantcast
Channel: Planet MySQL
Viewing all articles
Browse latest Browse all 1081

mysqlshによるJSONデータの取り込み(twitter api)

$
0
0

MySQL Shell経由でPythonで書いた処理をそのまま流し込めるので、
Twitter APIからJSONデータを取得して100件程データベースに流し込むデモを行いました。
PS: ネットワークがなぜか、共有WIFI、プライベートWIFI共に調子が悪く微妙な感じになってしまいましたが。。。

JSONデータ型、Generated Column(生成列)、MySQL Shellの挙動を簡易的にデモするものなので内容的には微妙ですが、
もしAPI経由でJSONデータを取得して、バッチ処理で定期的にサービスで使えそうなデータを取得して、
データを蓄積したり検索したい場合などに使えるかもしれません。

demo

————————————————————————
1) Create a Sample Table for Importing Data from Twitter API
————————————————————————
name列は、Tweetした人の名前が入ります。
text列は、Tweetしたコメントが入ります。


Create Table: CREATE TABLE `X_PYTHON` (
  `doc` json DEFAULT NULL,
  `_id` varchar(32) GENERATED ALWAYS AS (json_unquote(json_extract(`doc`,'$._id'))) STORED NOT NULL,
  `name` varchar(64) GENERATED ALWAYS AS (json_unquote(json_extract(`doc`,'$.user.name'))) STORED,
  `text` varchar(512) GENERATED ALWAYS AS (json_unquote(json_extract(`doc`,'$.text'))) STORED,
  UNIQUE KEY `_id` (`_id`),
  KEY `idx_name` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4

————————————————————————
2) Create python file ( demo_python_twitter.py )
————————————————————————
デモ用サンプルなので色々とコメントアウトしてます。またエラー処理も入れてません。
動作確認のみでご利用下さい。
※ Twitterキー、スキーマ、アカウントに関しては、適宜変更して下さい。
※ 必要に応じて、”pip install requests-oauthlib”でOauthもインストールしておいてください。


# coding: utf-8

print "======================================================"
print "MySQL5.7.12 Basic CRUD Operations by Python"
print "MySQL Innovation Daysデモ"
print "======================================================"

from requests_oauthlib import OAuth1Session
import json
import mysqlx

##############################################################
#    This section is just used for my private account.
##############################################################

api_key      = "Please put your own key"
api_secret   = "Please put your own key"
token        = "Please put your own key"
token_secret = "Please put your own key"

##############################################################
#    This section is API and Auth.
##############################################################

url = "https://api.twitter.com/1.1/statuses/home_timeline.json"
params = {'count':'100',}

auth = OAuth1Session(api_key, api_secret, token, token_secret)
res = auth.get(url, params = params)

##############################################################
#     Connect Session to the MySQL Instance.
##############################################################

if res.status_code == 200: # In case of successfully connect to API

 mySession = mysqlx.getSession({
 'host': 'localhost', 'port': 33060,
 'dbUser': 'demo_user', 'dbPassword': 'password'} )
 myDb = mySession.getSchema('NEW57')


### Create a new collection 'my_collection' ###
### This section is turned off for demo.    ###
# myColl = myDb.createCollection('X_PYTHON')


### Insert documents ###

 timeline = json.loads(res.text)
 for tweet in timeline:
   myDb.X_PYTHON.add(tweet).execute()
#  myDb.X_PYTHON.add(tweet).executeAsync() # ASYNCはmysqlshでは対象外.
#  print(tweet["text"])


####################################################
###         Drop the collection(Table)
####################################################
# mySession.dropCollection('NEW57','X_PYTHON')

else: # 失敗した場合
        print ("Error: %d" % req.status_code)

————————————————————————
3) Please Execute the Script through mysqlsh
————————————————————————
こちらは、Pythonモードで処理しています。


mysqlsh --py < demo_python_twitter.py

————————————————————————
4) You can find who is the most active user in twitter.
————————————————————————
mysqlshではパイプでつないで、リダイレクトする事が出来ます。


echo "select name,count(name) from X_PYTHON group by name order by count(name) desc limit 10;" | mysqlsh -u demo_user -ppassword --sql --schema=NEW57

実行結果(直近100件のTweet件数毎のデータ確認)


mysqlx: [Warning] Using a password on the command line interface can be insecure.
+---------------------------------------+-------------+
| name                                  | count(name) |
+---------------------------------------+-------------+
<snip>
| Tony Darnell                          |          13 |
| Giuseppe Maxia                        |           2 |
| planetmysql                           |           2 |
<snip>

name以外にtextにも生成列を設定しているので、コメントをフィルターする事も出来ます。
簡易デモなので何ですが、実用的な用途があれば簡単にJSONデータ処理出来るので色々なケースで使えるかもしれません。


root@localhost [NEW57]> desc X_PYTHON;
+-------+--------------+------+-----+---------+------------------+
| Field | Type         | Null | Key | Default | Extra            |
+-------+--------------+------+-----+---------+------------------+
| doc   | json         | YES  |     | NULL    |                  |
| _id   | varchar(32)  | NO   | PRI | NULL    | STORED GENERATED |
| name  | varchar(64)  | YES  | MUL | NULL    | STORED GENERATED |
| text  | varchar(512) | YES  |     | NULL    | STORED GENERATED |
+-------+--------------+------+-----+---------+------------------+
4 rows in set (0.00 sec)

root@localhost [NEW57]> 

PlanetMySQL Voting: Vote UP / Vote DOWN

Viewing all articles
Browse latest Browse all 1081

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>