简体   繁体   English

Javascript Neo4j 驱动 Json 解析快递 Z8A5DA52ED126447D359E70C05AZ721AA8

[英]Javascript Neo4j Driver Json parse express api

This may be a non-issue however I can't help but feel like there is a better way to do what I am trying to achieve.这可能不是问题,但我不禁觉得有更好的方法来做我想要实现的目标。

I am writing an API in Express with my data stored in a neo4j database.我正在 Express 中编写 API,我的数据存储在 neo4j 数据库中。 I am using the official neo4j-driver to interface with neo4j which is running locally.我正在使用官方的 neo4j-driver 与本地运行的 neo4j 接口。 When I run a query eg:当我运行查询时,例如:

session
    .run(`MATCH (foo:FamilyMember)-[:HAS_SISTER]->(sister:FamilyMember)
    WHERE foo.firstName = 'bar'
    RETURN sister.firstName AS Name, sister.lastName AS Surname
    `)
    .then(res => {
        console.log(res);
    })

Neo4j returns a response object with a lot of information about the request: Neo4j 返回响应 object ,其中包含有关请求的大量信息:

{
  records: [
    Record {
      keys: [Array],
      length: 2,
      _fields: [Array],
      _fieldLookup: [Object]
    },
    Record {
      keys: [Array],
      length: 2,
      _fields: [Array],
      _fieldLookup: [Object]
    },
    Record {
      keys: [Array],
      length: 2,
      _fields: [Array],
      _fieldLookup: [Object]
    },
    Record {
      keys: [Array],
      length: 2,
      _fields: [Array],
      _fieldLookup: [Object]
    }
  ],
  summary: ResultSummary {
    query: {
      text: 'MATCH (foo:FamilyMember)-[:HAS_SISTER]->(sister:FamilyMember)\n' +
        "    WHERE foo.firstName = 'bar'\n" +
        '    RETURN sister.firstName AS Name, sister.lastName AS Surname\n' +
        '    ',
      parameters: {}
    },
    queryType: 'r',
    counters: QueryStatistics { _stats: [Object], _systemUpdates: 0 },
    updateStatistics: QueryStatistics { _stats: [Object], _systemUpdates: 0 },
    plan: false,
    profile: false,
    notifications: [],
    server: ServerInfo {
      address: 'localhost:7687',
      version: 'Neo4j/4.2.1',
      protocolVersion: 4.2
    },
    resultConsumedAfter: Integer { low: 0, high: 0 },
    resultAvailableAfter: Integer { low: 4, high: 0 },
    database: { name: 'neo4j' }
  }
}

This is a pain when really I what I want is either the actual response data as an array of objects or an error message if something fails.当我真正想要的是作为对象数组的实际响应数据或失败时的错误消息时,这很痛苦。

I wrote this parse method to generate an array of Javascript object's with the data returned from the query:我编写了这个解析方法来生成一个 Javascript 对象的数组,其中包含从查询返回的数据:

function parseNeo4jResponseJSON(res) {
    return results = res.records.reduce( (array, currentRecord) => {
        const record = currentRecord.keys.reduce( (obj, key, index) => {
            obj[key] = currentRecord._fields[index]
            return obj
        }, {})
        array.push(record);
        return array;
    },[])
};

This works and now when I console log the query response through my parser I get it in the format I want eg:这有效,现在当我通过解析器控制台记录查询响应时,我以我想要的格式得到它,例如:

[
  { Name: 'foo', Surname: 'bar' },
  { Name: 'foo2', Surname: 'bar2' },
  ...
]

Is this approach going to cause me problems down the line?这种方法会给我带来麻烦吗? Is there a better way to get a javascript object from the response?有没有更好的方法从响应中获取 javascript object ? I am pretty new to neo4j.我对 neo4j 很陌生。 Apologies if the answer is obvious.如果答案很明显,请道歉。

Based on the existing examples , what about:基于现有示例,如何:

session
    .readTransaction((tx) => 
       tx.run(`MATCH (foo:FamilyMember)-[:HAS_SISTER]->(sister:FamilyMember)
               WHERE foo.firstName = 'bar'
               RETURN sister.firstName AS Name, sister.lastName AS Surname`)
    )
    .then(results => results.records.map((record) => {
       return {
              Name: record.get('Name'),
              Surname: record.get('Surname')
       }
    })

You could keep session.run , but the session.{read,write}Transaction variants are usually recommended because they work in every environment (where session.run may sometimes fail in a cluster environment).您可以保留session.run ,但是session.{read,write}Transaction 通常建议使用事务变体,因为它们在每个环境中都有效(其中session.run有时可能会在集群环境中失败)。

Please also make sure to use a dictionary of parameters (2nd argument of tx.run ) instead of using string interpolation, if your query needs to be parameterized.如果您的查询需要参数化,还请确保使用参数字典( tx.run的第二个参数)而不是使用字符串插值。 If the value of foo.firstName comes from a variable (let's say someFirstName ), the tx.run would become:如果foo.firstName的值来自一个变量(比如说someFirstName ),则tx.run将变为:

tx.run("MATCH (foo:FamilyMember)-[:HAS_SISTER]->(sister:FamilyMember)
               WHERE foo.firstName = $firstName
               RETURN sister.firstName AS Name, sister.lastName AS Surname",
       {firstName: someFirstName})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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