我正在使用 Python ,Tweepy
和MySQLdb
模块构建一个twitter抓取器应用程序
它将获取数百万条推文,因此性能是一个问题 我想检查表中之前是否存在tweet_id,然后再将其添加到同一个Query
中表模式是:
*id* | tweet_id | text
_____|________________________|______________________________
1 | 259327533444925056 | sample tweet1
_____|________________________|______________________________
2 | 259327566714923333 | this is a sample tweet2
我尝试过的代码是双重查询:
#check that the tweet doesn't exist first
q = "select count(*) from tweets where tweet_id = " + tweet.id
cur.execute(q)
result = cur.fetchone()
found = result[0]
if found == 0:
q = "INSERT INTO lexicon_nwindow (tweet_id,text) VALUES(tweet_id,tweet.text)
cur.execute(q)
使Tweet_id唯一且只是插入推文,会引发异常并且也不会有效吗?
那么使用一个查询实现这一目标的最佳方法是什么?
答案 0 :(得分:1)
如果将tweet_id作为主键(drop field Id),则可以使用INSERT IGNORE或REPLACE INTO。 1中解决了2个问题。
如果要保留Id字段,请将其设置为索引/唯一并将其设置为自动增量。如果我知道tweet_id可以用作主键,我会避开这种方法。
希望这有帮助。
哈
答案 1 :(得分:0)
#check that the tweet doesn't exist first
q = "select count(*) from tweets where tweet_id = " + tweet.id
cur.execute(q)
result = cur.fetchone()
found = result[0]
if found == 0:
q = "REPLACE lexicon_nwindow (tweet_id,text) VALUES(tweet_id,tweet.text)
cur.execute(q)
答案 2 :(得分:0)
使用INSERT SELECT而不是INSERT VALUES,并在SELECT中添加一个WHERE子句来检查你的tweet.id是否已经在表中
q = "INSERT INTO lexicon_nwindow (tweet_id,text)
SELECT " + tweet.id +" ," + tweet.text +" FROM DUAL
WHERE not exists(select 1 from tweets where tweet_id = " + tweet.id +" ) "
答案 3 :(得分:0)
答案是个人资料,不要推测。
我不是故意不屑一顾。我们不知道最快的是什么:
我们不知道数据的速率,重复的频率,服务器配置,是否有多个写入器同时等等。
个人资料,不要推测。