Search code examples
azuregremlin

How to get single values from am gremlinquery in C# code


I am using gremlin with Azure Cosmos DB. I'm using this code to get a list of files from a graph database.

    public async Task<List<string>> GetFilesWithMoreThanOneFilename()
    {
        List<string> list = new List<string>();
        using (var gremlinClient = new GremlinClient(gremlinServer, new GraphSON2Reader(), new GraphSON2Writer(), GremlinClient.GraphSON2MimeType))
        {
            var resultSet = await gremlinClient.SubmitAsync<dynamic>("g.V().hasLabel('file').where(out().count().is(gt(1)))");
            if (resultSet.Count > 0)
            {
                foreach (var result in resultSet)
                {
                    string output = JsonConvert.SerializeObject(result);
                    list.Add(output);
                }
            }
        }
        return list;
    }

The output string looks like this:

{"id":"0a37e4896b6310b6d152f6cf89336173ffb89b819f7955494322e0f0bec017b4","label":"file","type":"vertex","properties":{"fileSize":[{"id":"456b087c-7cf3-43ea-a482-0f31219bc520","value":"41096"}],"mimeType":[{"id":"d849b065-16f8-465b-986c-f8e0fdda9ac7","value":"text/plain"}]}}

My Question is how I can get a single value from the result. For example just the ID or the mimeType or is the only possiblity to work with the output and string manipulation?


Solution

  • Due to your output data is in json format, so you could use Newtonsoft.Json to read the data.

    I create a json file with your data, you could just parse the json data without file. And just read the id and properties.fileSize

    static void Main(string[] args)
        {
    
            JObject jsonData = JObject.Parse(File.ReadAllText( "test.json"));
            Console.WriteLine("id:"+jsonData["id"].ToString());
            Console.WriteLine("properties:"+jsonData["properties"]["fileSize"].ToString());
            Console.ReadLine(); 
        }
    

    And here is the result:

    enter image description here

    Hope this could help you, if yo ustill have other questions, please let me know.

    Update: if you want to get the value in the array, you could use this to get the value:

     Console.WriteLine("mimeType.value:" + jsonData["properties"]["mimeType"][0]["value"].ToString());
    

    enter image description here