简体   繁体   中英

How to search on Cosmos DB in a complex JSON Object

I have the following JSON Object, as you can see it references a TAG object, which is an array of tags.

public class GlobalPageTemplate : ISharedCosmosEntity
{
    [JsonProperty("Id")]
    public string Id { get; set; }

    [CosmosPartitionKey]
    public string CosmosEntityName { get; set; }

    public string Description { get; set; }
    public string ExtractedPageName { get; set; }
    public string ExtractedSitecollectionTemplateName { get; set; }
    public string ExtractedGlobalDesignTenantId { get; set; }
    public string ExtractedGlobalDesigntenantSiteCollectionUrl { get; set; }
    public string PageTemplatePictureUrl { get; set; }
    public string Base64Image { get; set; }
    public string PageTemplateName { get; set; }
    public List<Section> Sections { get; set; }
    public string TemplateAccessLevel { get; set; }
    public List<Tag> Tags { get; set; }
}

public class Tag : ISharedCosmosEntity
{

    [JsonProperty("Id")]
    public string Id { get; set; }

    public string TagName { get; set; }

    [CosmosPartitionKey]
    public string CosmosEntityName { get; set; }
}

In the database, objects are saved like this:

{
    "CosmosEntityName": "globalpagetemplates",
    "Description": "depper",
    "ExtractedPageName": "Home.aspx",
    "ExtractedSitecollectionTemplateName": "CommunicationSite",
    "ExtractedGlobalDesignTenantId": "696da7e7-a03e-4996-bbf8-625b8e4c4c06",
    "ExtractedGlobalDesigntenantSiteCollectionUrl": "https://xx.sharepoint.com/sites/TST1",
    "PageTemplatePictureUrl": "https://xx.blob.core.windows.net/globalpagetemplatespictures/0befc979-3958-4e27-a345-f4ce491eb1ee.png",
    "Base64Image": "",
    "PageTemplateName": "Plantilla 5 TST 1",
    "Sections": [],
    "TemplateAccessLevel": "Platinum",
    "Tags": [
        {
            "Id": null,
            "TagName": "recursos humanos",
            "CosmosEntityName": null
        }
    ],
    "id": "0befc979-3958-4e27-a345-f4ce491eb1ee",
    "_rid": "q6JzALvx8ZHMCQAAAAAAAA==",
    "_self": "dbs/q6JzAA==/colls/q6JzALvx8ZE=/docs/q6JzALvx8ZHMCQAAAAAAAA==/",
    "_etag": "\"35001a26-0000-0300-0000-5df77cf60000\"",
    "_attachments": "attachments/",
    "_ts": 1576500470
}

I have a method that returns ALL page templates:

/// <returns></returns>
[HttpGet]
public async Task<IHttpActionResult> GetGlobalPageTemplates()
{ 
    var telemetry = new TelemetryClient();
    try
    {
        var globalPageTemplateStore = CosmosStoreHolder.Instance.CosmosStoreGlobalPageTemplate;
        var globalPageTemplates =  await globalPageTemplateStore.Query().ToListAsync();
        return Ok(globalPageTemplates);
    }
    catch (Exception ex)
    {
        string guid = Guid.NewGuid().ToString();
        var dt = new Dictionary<string, string>
        {
            { "Error Lulo: ", guid }
        };

        telemetry.TrackException(ex, dt);
        return BadRequest("Error Lulo: " + guid);
    }
}

However in the front end I can filter on TAGS,

So I need to create a method that receives a list of strings and then makes the query to get the page templates that matches the TAGS, the filter should be exclusive, I mean OR.

/// <returns></returns>
[HttpGet]
public async Task<IHttpActionResult> GetGlobalPageTemplatesByTags(List<string> tags)
{ 
    var telemetry = new TelemetryClient();
    try
    {
        var globalPageTemplateStore = CosmosStoreHolder.Instance.CosmosStoreGlobalPageTemplate;
        var globalPageTemplates =  await globalPageTemplateStore.Query().Where???
    }
    catch (Exception ex)
    {
        string guid = Guid.NewGuid().ToString();
        var dt = new Dictionary<string, string>
        {
            { "Error Lulo: ", guid }
        };

        telemetry.TrackException(ex, dt);
        return BadRequest("Error Lulo: " + guid);
    }
}

any idea how to achieve this?

You can try this query using Where() , Any() and Contains() from LINQ:

var globalPageTemplates = await globalPageTemplateStore
    .Query()
    .Where(template => template
        .Tags
        .Any(tag => tags.Contains(tag.TagName))
     )
     .ToListAsync();

If you want faster O(1) lookups for tags , I suggest converting it to a HashSet<string> beforehand:

var tagLookups = new HashSet<string>(tags);

var globalPageTemplates = await globalPageTemplateStore
    .Query()
    .Where(template => template
        .Tags
        .Any(tag => tagLookups.Contains(tag.TagName))
    )
    .ToListAsync();

The basic idea is to first filter each template with Where() , then check if Any() of the template tags exist in tags using Contains() .

Note: You must add ToListAsync() to the end of the query to convert the IQueryable<GlobalPageTemplate> to a List<GlobalPageTemplate> . This is because the query is asynchronous.

I believe, you are looking for a solution to filter GlobalPageTemplate matching with TagName in List<string> tags ; if yes, you can use .Where with .Any and .Contains of List

Sample Code

var globalPageTemplateStore = CosmosStoreHolder.Instance.CosmosStoreGlobalPageTemplate;
var globalPageTemplates =  await globalPageTemplateStore.Query()
    .Where(.Where(c => c.Addresses.Any(a => cityList.Contains(a.City)))
    .ToList();

Note: This will only work for Client Evaluation and you may need to use .AsEnumerable

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM