[英]MongoDB: How to realize an lookup dictionary for checking text
我想實現一個字典來檢查某些文本的正確拼寫。 在這本詞典中有20.000個單詞。 我的應用程序(這是一個流星應用程序)將首先加載文本。 現在,我將把該文本拆分為單詞,然后檢查每個單詞是否在詞典中。
但這在技術上是最好的方法嗎? 包含100個單詞的文本將有100個DB調用,感覺不好。 但是對我來說,在數組中完全加載20.000個單詞以進行查找也沒有意義...
let incorrect = [];
text.split(' ').forEach(word => {
if (!Dictionary.findOne({ word: word })) {
incorrect.push(word);
}
})
if (incorrect.length)
console.log('There is a spelling mistake');
else
console.log('Everything seems to be correct');
我想到的另一種方法是在查詢中發送帶有拆分單詞的數組,並獲取所有缺少的元素作為結果(數組)。 但是我不知道mongoDB是否可以做到這一點。
您會在數據庫中找到文本中的所有單詞。 因此,如果文本包含100個單詞,則應該分別有100個文檔,如果不是,則意味着文本有問題:
const arr = text.split(' ');
const wordCount = arr.length;
const docCount = Dictionary.find({
word: {
$in: arr,
},
}).count();
if (wordCount !== docCount) {
console.log('There is a spelling mistake');
}
更新
如果需要獲取拼寫錯誤的單詞,則只需對arr輸入使用diff函數,並在db中找到結果單詞。 我想您已經安裝underscore
,我使用_.difference獲得結果:
const arr = text.split(' ');
const foundWord = Dictionary.find({
word: {
$in: arr,
},
}).map(obj => obj.word);
const misspelledWords = _.difference(arr, foundWord);
console.log(misspelledWords);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.