2013-10-12 52 views
0

我正在開發Twitter數據的分析程序。 我現在正在使用mongoDB。我嘗試編寫一個Java程序來從Twitter API獲取推文並將它們放入數據庫中。 獲取Tweets已經運行得很好,但當我想將它們放入數據庫時​​遇到問題。由於Twitter API通常只返回相同的Tweets,我必須在數據庫中放置某種索引。避免使用Java和JSON對象在mongoDB中重複輸入

首先,我連接到數據庫並獲取與搜索項相關的集合,或者如果不存在,則創建此集合。

public void connectdb(String keyword) 
     { 
      try { 
       // on constructor load initialize MongoDB and load collection 
       initMongoDB(); 
       items = db.getCollection(keyword); 
       BasicDBObject index = new BasicDBObject("tweet_ID", 1); 
       items.ensureIndex(index); 



      } catch (MongoException ex) { 
       System.out.println("MongoException :" + ex.getMessage()); 
      } 

     } 

然後我得到的鳴叫,並把它們在數據庫:

public void getTweetByQuery(boolean loadRecords, String keyword) { 

      if (cb != null) { 
       TwitterFactory tf = new TwitterFactory(cb.build()); 
       Twitter twitter = tf.getInstance(); 
       try { 
        Query query = new Query(keyword); 
        query.setCount(50); 
        QueryResult result; 
        result = twitter.search(query); 
        System.out.println("Getting Tweets..."); 
        List<Status> tweets = result.getTweets(); 

        for (Status tweet : tweets) { 

         BasicDBObject basicObj = new BasicDBObject(); 
         basicObj.put("user_name", tweet.getUser().getScreenName()); 
         basicObj.put("retweet_count", tweet.getRetweetCount()); 
         basicObj.put("tweet_followers_count", tweet.getUser().getFollowersCount()); 

         UserMentionEntity[] mentioned = tweet.getUserMentionEntities(); 
         basicObj.put("tweet_mentioned_count", mentioned.length); 
         basicObj.put("tweet_ID", tweet.getId()); 
         basicObj.put("tweet_text", tweet.getText()); 


         if (mentioned.length > 0) { 
//     System.out.println("Mentioned length " + mentioned.length + " Mentioned: " + mentioned[0].getName()); 
         } 
         try { 
          items.insert(basicObj); 
         } catch (Exception e) { 
          System.out.println("MongoDB Connection Error : " + e.getMessage()); 
          loadMenu(); 
         } 
        } 
        // Printing fetched records from DB. 
        if (loadRecords) { 
         getTweetsRecords(); 
        } 

       } catch (TwitterException te) { 
        System.out.println("te.getErrorCode() " + te.getErrorCode()); 
        System.out.println("te.getExceptionCode() " + te.getExceptionCode()); 
        System.out.println("te.getStatusCode() " + te.getStatusCode()); 
        if (te.getStatusCode() == 401) { 
         System.out.println("Twitter Error : \nAuthentication credentials (https://dev.twitter.com/pages/auth) were missing or incorrect.\nEnsure that you have set valid consumer key/secret, access token/secret, and the system clock is in sync."); 
        } else { 
         System.out.println("Twitter Error : " + te.getMessage()); 
        } 


        loadMenu(); 
       } 
      } else { 
       System.out.println("MongoDB is not Connected! Please check mongoDB intance running.."); 
      } 
     } 

但正如我前面提到的,經常有相同的微博,和他們在數據庫中的重複。 我認爲tweet_ID字段對於索引是一個很好的字段,並且在集合中應該是唯一的。

回答

0

設置你的指數unique選項,MongoDB的強制唯一性:

items.ensureIndex(index, new BasicDBObject("unique", true)); 

請注意,您需要手動刪除現有的索引並刪除所有重複,否則您將無法創建獨特的索引。

+0

或在您傳遞的BasicDBObject上放置(「dropDups」,true)。 – evanchooly

0

這個問題已經回答了,但我想既然MongoDB API 2.11提供接收唯一選項作爲參數的方法貢獻了一下:

public void ensureIndex(DBObject keys, String name, boolean unique) 

A小調提醒某人想在存儲JSON文檔誰MongoDBNote是唯一性必須應用於BasicObject鍵而不是值。例如:

BasicDBObject basicObj = new BasicDBObject(); 
basicObj.put("user_name", tweet.getUser().getScreenName()); 
basicObj.put("retweet_count", tweet.getRetweetCount()); 
basicObj.put("tweet_ID", tweet.getId()); 
basicObj.put("tweet_text", tweet.getText()); 
basicObj.put("a_json_text", "{"info_details":{"info_id":"1234"},"info_date":{"year":"2012"}, {"month":"12"}, {"day":"10"}}"); 

在這種情況下,你只能以基本對象鍵創建唯一索引:

BasicDBObject index = new BasicDBObject(); 
int directionOrder = 1; 
index.put("tweet_ID", directionOrder); 
boolean isUnique = true; 
items.ensureIndex(index, "unique_tweet_ID", isUnique); 

任何有關指數像JSON值「info_id」不會因爲it's工作不是BasicObject鍵。

在MongDB上使用索引並不像聽起來那麼容易。您也可以在這裏檢查MongoDB文檔以獲取更多詳細信息Mongo Indexing TutorialsMongo Index Concepts。一旦你需要一個組合索引,在這裏很好地解釋Why Direction order matter,方向順序可能是非常重要的理解。