Как передать функцию Python функции pymongo map_reduce (bson.code)? - PullRequest
0 голосов
/ 13 мая 2019

Я искал на разных форумах, но не могу найти правильный ответ на мой вопрос.

Я использую pymongo bson.code для преобразования в карту коллекции документов с именем MediaSummary , присутствующей в моем MongoDB. Результирующая коллекция будет представлять собой список уникальных (без остановок) слов, каждое из которых содержит соответствующие идентификаторы документов.

Данные для сбора, например, следующие:

{_id: "abc", VideoData: "This video contains documentary info about Universe."}
{_id: "def", VideoData: "This video is about Milkyway."}
{_id: "ghi", VideoData: "This video is about Earth and its importance."}

Код Python:

import pymongo
from nltk.corpus import stopwords 
from nltk.tokenize import word_tokenize

from pymongo import MongoClient
from bson.code import Code

client = MongoClient('mongodb://myuser:abc123@my-server/DataSummary')

db = client['DataSummary']

def getFilteredSentence(sentence):

    stop_words = set(stopwords.words('english')) 
    word_tokens = word_tokenize(sentence) 
    words = [word for word in word_tokens if word.isalpha()]  # remove punctuation
    filteredSentence = [] 

    for w in words:
        if (w and w.strip()):
            if w.lower() not in stop_words: 
                filteredSentence.append(w.strip().lower()) 

    return filteredSentence

Функция картографирования:

mapper = Code(""" 
           function map() {
            if (!this.VideoData) return;

            var key = this._id.toString();
            var value = getFS(this.VideoData); // getFS is a Python function passed to it via scope. It filters out the stop words from sentence.

            emit(key, value);
          };
          """

)

Функция редуктора:

reducer = Code("""
               function reduce(key, values) {
                   uniqueWordsWithDocIds = [];
                   // Some further processing on values

                   return uniqueWordsWithDocIds 
               };
               """

Вызов map_reduce для MediaSummary collection:

output_collection = db.MediaSummary.map_reduce(
    mapper, reducer, 'SearchWords',
    scope = {
        'getFS': somePyThonFuncForFilteringOutStopWords  # This must be a Python function that I can make use of in my mapper function
    })

Нужна помощь. Пожалуйста, руководство.

...