2016-09-19 97 views
0

我試圖使用IN過濾器查詢DynamoDB表。當我將單個值傳遞給IN時,我的查詢起作用,但是當我傳入多個時,我得不到任何匹配。使用IN過濾DynamoDB查詢使用IN

這裏是params對象的初始設置。

var params = { 
    TableName: "Interactions", 
    IndexName: "environment-time-index", 
    KeyConditionExpression: "#environment = :environment and #time between :start and :end", 
    FilterExpression: "#product = :product", 
    ExpressionAttributeNames: { 
     "#product": "product", 
     "#environment": "environment", 
     "#time": "time" 
    }, 
    ExpressionAttributeValues: { 
     ":product": product,  
     ":environment": environment, 
     ":start": start, 
     ":end": end 
    } 
    }; 

接下來,如果用戶提供了一個固定的查詢參數,我修改了params對象,就像這樣。這是我使用IN操作符的地方。

if (req.query.firm) { 
    var firms = req.query.firm; 
    console.log('debug', firms); 
    params.FilterExpression += " AND #firmCode IN (:firms)"; 
    params.ExpressionAttributeNames["#firmCode"] = "firmCode"; 
    params.ExpressionAttributeValues[":firms"] = firms; 
    } 

最後,我運行查詢,就像這樣。

docClient.query(params, function(err, data) { 
    if (err) { 
     log.error(`Unable to scan. Error: ${JSON.stringify(err, null, 2)}`); 
     res.status(500).json({ error: "Oh, snap!" }); 
    } else { 
     data.Parameters = params.ExpressionAttributeValues; 
     log.info(`Scan succeeded. Received ${data.Count} items.`) 
     res.send(data); 
    } 
    }); 

當公司參數包含單個值時,我會返回結果。

Level="INFO", Date="2016-09-19 14:26:03,373", Message="batchinsight received GET for /api/history/interactions2", Product="Exhaust", Service="batchinsight", AppDomain="Exhaust_batchinsight" 
debug TW7ZN 
Level="INFO", Date="2016-09-19 14:26:03,623", Message="Scan succeeded. Received 19 items.", Product="Exhaust", Service="batchinsight", AppDomain="Exhaust_batchinsight" 

但是當它包含多個值時,我沒有得到任何結果。

Level="INFO", Date="2016-09-19 14:35:16,896", Message="batchinsight received GET for /api/history/interactions2", Product="Exhaust", Service="batchinsight", AppDomain="Exhaust_batchinsight" 
debug TW7ZN,TEXK4 
Level="INFO", Date="2016-09-19 14:35:16,991", Message="Scan succeeded. Received 0 items.", Product="Exhaust", Service="batchinsight", AppDomain="Exhaust_batchinsight" 

DynamoDB文檔建議IN運算符可以接受以逗號分隔的值列表,但我無法使其工作。請幫忙! http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.SpecifyingConditions.html#ConditionExpressionReference

回答

1

實際上,您指的是與FilterExpression不同的ConditionExpression參考文檔。

條件表達式表示當您閱讀時(請不要將其與查詢/掃描混淆)並在表中寫入項目時實施限制。

您實際上正在查詢表格。 FilterExpression用於查詢和掃描數據。

IN:檢查兩組內的匹配元素。 AttributeValueList 可以包含一個或多個String類型的AttributeValue元素, 數字或二進制(不是集合類型)。將這些屬性與項目的現有設置類型屬性進行比較 。如果 的任何元素的輸入集存在於項目屬性中,則表達式 的計算結果爲true。

請注意,IN用於檢查SET數據類型中是否存在單個值。

您可以參考類似的帖子here其中OR條件用於比較SET數據類型中的多個值。

同樣,如果firmCode是STRING或SET數據類型,則應使用或條件