Search code examples
c#neo4jclient

Neo4j- how to use WITH clause using c# client cypher


I am trying to get the results using WITH clause in C# neo4j client.
Since I am new to neo4j, I do not have any idea on how to get the results in C#.
Please help me with your suggestions

MATCH (cs:CrawlerInfo)
WITH cs, SIZE((cs)-[:CONTAINS]->()) as TotalResult
RETURN 
cs.CrawlerName,cs.Keyword,cs.SearchType,toint(TotalResult),cs.CrawlerInfoDate
order by toint(cs.CrawlerId) desc

Solution

  • In Neo4jClient straight translation is the key, and should be discoverable via the API.

    //gc = GraphClient instance
    //CrawlerInfo is a class
    gc.Cypher
        .Match("(cs:CrawlerInfo)")
        .With("cs, SIZE( (cs)-[:CONTAINS]->() ) as TotalResult")
        .Return((cs, TotalResult) => new
        {
            CrawlerName = cs.As<CrawlerInfo>().CrawlerName,
            Keyword = cs.As<CrawlerInfo>().Keyword,
            SearchType = cs.As<CrawlerInfo>().SearchType,
            CrawlerInfoDate = cs.As<CrawlerInfo>().CrawlerInfoDate,
            Size = Return.As<int>("toint(TotalResult)")
        })
        .OrderByDescending("toint(cs.CrawlerId)");
    

    Personally, I would make my CrawlerInfo class look something like:

    public class CrawlerInfo
    {
        public int CrawlerId { get; set;}
        public string CrawlerName { get; set; }
        public string Keyword { get; set; }
        public string SearchType { get; set; }
        public string CrawlerInfoDate { get; set;}
    }
    

    Then you also don't/(shouldn't!) need to do the toint, which means you can do:

    gc.Cypher
        .Match("(cs:CrawlerInfo)")
        .With("cs, SIZE( (cs)-[:CONTAINS]->() ) as TotalResult")
        .Return((cs, TotalResult) => new
        {
            CrawlerName = cs.As<CrawlerInfo>().CrawlerName,
            Keyword = cs.As<CrawlerInfo>().Keyword,
            SearchType = cs.As<CrawlerInfo>().SearchType,
            CrawlerInfoDate = cs.As<CrawlerInfo>().CrawlerInfoDate,
            Size = Return.As<int>("TotalResult")
        })
        .OrderByDescending("cs.CrawlerId");
    

    Which is a bit tidier. I'd also be tempted to just return the CrawlerInfo object itself, rather than the properties (or make a small CrawlerInfoLite model if CrawlerInfo is massive):

    gc.Cypher
        .Match("(cs:CrawlerInfo)")
        .With("cs, SIZE((cs)-[:CONTAINS]->()) as TotalResult")
        .Return((cs, TotalResult) => new
        {
            CrawlerInfo = cs.As<CrawlerInfo>(),
            Size = Return.As<int>("TotalResult")
        })
        .OrderByDescending("cs.CrawlerId");
    

    Where CrawlerInfo is defined as:

    public class CrawlerInfo
    {
        public int CrawlerId { get; set;}
        public string CrawlerName { get; set; }
        public string Keyword { get; set; }
        public string SearchType { get; set; }
        public string CrawlerInfoDate { get; set;}
    }