2013-01-31 8 views
6

私はMongoEngineをウェブスクレイピングプロジェクトで使用しています。私はすべての掻き集められたウェブページで私が遭遇したすべての画像を追跡したいと思います。Mongoengine - 「新しいアイテムを保存するか、カウンタを増やす」操作を実行するには?

これを行うには、画像srcのURLと画像が表示された回数を保存します。

MongoEngineモデル定義は次のとおりです。

class ImagesUrl(Document): 
    """ Model representing images encountered during web-scraping. 

    When an image is encountered on a web-page during scraping, 
    we store its url and the number of times it has been 
    seen (default counter value is 1). 
    If the image had been seen before, we do not insert a new document 
    in collection, but merely increment the corresponding counter value. 

    """ 

    # The url of the image. There cannot be any duplicate. 
    src = URLField(required=True, unique=True) 

    # counter of the total number of occurences of the image during 
    # the datamining process 
    counter = IntField(min_value=0, required=True, default=1) 

私は「保存または増分」プロセスを実施するための適切な方法を探しています。

これまでのところ、私はそのように扱うんだけど、私はMongoEngineでそれを行うためのより良い、組み込みの方法があるかもしれないと感じ:

def save_or_increment(self): 
    """ If it is the first time the image has been encountered, insert 
     its src in mongo, along with a counter=1 value. 
     If not, increment its counter value by 1. 

    """ 
    # check if item is already stored 
    # if not, save a new item 
    if not ImagesUrl.objects(src=self.src): 
     ImagesUrl(
      src=self.src, 
      counter=self.counter, 
      ).save() 
    else: 
     # if item already stored in Mongo, just increment its counter 
     ImagesUrl.objects(src=self.src).update_one(inc__counter=1) 

はそれを行うための良い方法はありますか?

ありがとうございます。

答えて

10

あなただけupsert例えば行うことができる必要があります:

ImagesUrl.objects(src=self.src).update_one(
            upsert=True, 
            inc__counter=1, 
            set__src=self.src) 
+0

おかげで、それは完全に働きました! –

+0

ところで、Document.save()関数をこの動作でオーバーライドするか、新しいImagesUrlメソッドで実装することをお勧めしますか? –

+0

私は 'save'を使用しないことをお勧めします。その目的は明確ではありません - 私は' update_one'コードを実行します。 – Ross

関連する問題