使用连接和数组

时间:2015-09-01 14:15:21

标签: sql linq azure azure-cosmosdb

有没有办法用 Linq (对于DocumentDB)为DocumentDB制定以下SQL语句?

SELECT docs
FROM docs
JOIN tags IN docs.tags
WHERE tags IN ("B", "C")

这是基于我的问题及DocumentDB queries with arrays的答案。

3 个答案:

答案 0 :(得分:1)

在我的(非常通用的)存储库中,我为WHERE谓词动态构建了一些复杂的表达式。 因此,手动创建SQL语句实际上并不是一种选择。

所以我最终使用了用户定义的函数。

在具有ID:CONTAINSANY

的Collection中定义的UDF
function containsAny (source, target) {
    if (source == null || target == null) return false;
    return target.some(function(item) { return source.indexOf(item) >= 0; } );
}

客户致电:

var udfName = "CONTAINSANY";    
var tags = new[] { "B", "C" };
var query = client.CreateDocumentQuery(collLink)
     .Where(item => (bool)UserDefinedFunctionProvider.Invoke(udfName, item.tags, tags);

答案 1 :(得分:0)

如果你有这样的课程

public class Doc
{
    [JsonProperty(PropertyName = "id")]
    public string Id { get; set; }
    public string[] Tags{ get; set; }
}

您可以这样做:

private string EndpointUrl = "<your endpoint URI>";
private string AuthorizationKey = "<your key>";
private string database = "<DB Id>";
private string CollectionID= "<Collection Id>";

//prepare document db client
DocumentClient pClient = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey);

//prepare document db database
Database pDatabase = pClient.CreateDatabaseQuery().Where(db => db.Id == database).AsEnumerable().FirstOrDefault();

//prepare document db collection
DocumentCollection documentCollection= pClient.CreateDocumentCollectionQuery(pDatabase.SelfLink).Where(c => c.Id == CollectionID).ToArray().FirstOrDefault();

var tags = new[] { "B", "C" };
var families =  client.CreateDocumentQuery<Doc>(documentCollection.DocumentsLink)
               .SelectMany(doc=>doc.Tags.Where(t=> tags.Contains(t));

现在我不确定Linq提供商是否已经支持Contains方法(我没有找到任何关于该方法的文档),但如果没有,也许你可以完成你这样的条件:

.Where(t=>t=="B" || t=="C") 

我知道这不太理想,但应该有效。所有这些都是新的,我们必须稍等一下才能看到更多的文档以及我们可以使用的更多功能。

同时,总是可以选择直接执行您的查询:

var items = client.CreateDocumentQuery<dynamic>(documentCollection.DocumentsLink,
    "SELECT docs" +
    "FROM docs" +
    "JOIN tags IN docs.tags" +
    "WHERE tags IN (\"B\", \"C\")");

您可以在此link

中找到有关如何在DocumentDb中创建查询的详细信息

答案 2 :(得分:0)

Ever since v 1.4.0 of the .NET SDK the following is now supported -

string[] ids = new string[] { "1", "2", "3", "4", "5"};
var query = client.CreateDocumentQuery(collLink).Where(d => ids.Contains(d.Id);