问题
So I'm trying to actually write an answer to this question which seemed like an interesting one to me. What the hell, I'll give it a shot.
Here's the solution I came up with. It seems correct to me, and should yield the right result, but instead yields a cypher parse error.
So the game here is to take two collections (letters and numbers) and to construct a map out of them which maps the right letter to the right number, sequentially from the two collections.
My solution:
with [1,2,3] as nums, ['a', 'b', 'c'] as letters
with nums, letters, range(0, length(nums)-1) as idxs
return extract(idx in idxs | { letters[idx] : nums[idx] });
My reasoning is that I need to iterate over collection indexes so that I can use the same index to "advance both collections" at the same time. I'm using extract
to get each index, then constructing the nested map, which pairs the appropriate items.
Except that it fails because cypher says:
Invalid input '[': expected an identifier character, whitespace, '}' or ':' (line 3, column 39 (offset: 140))
"return extract(idx in idxs | { letters[idx] : nums[idx] });"
^
UPDATE: cybersam answered the original question here and indicated that "it may not be possible to dynamically create map keys". So my real question is -- is that accurate (maps cannot have dynamic keys) and if so, why?
回答1:
This is just the "limitation" of cypher. You can try this:
WITH 'a' as key, 'test' as value
RETURN {key: value}
but the result is this:
{"key":"test"}
The correct approach is shown in the answer of Cybersam. Something like this:
WITH 'a' as key, 'test' as value, 'b' as key2, 'test2' as value2
RETURN [{key: key, value: value}, {key: key2, value: value2}]
will results:
[{"key":"a","value":"test"},{"key":"b","value":"test2"}]
For creating dynamic map keys you have to use java or other programming languages.
来源:https://stackoverflow.com/questions/29265673/constructing-a-map-doesnt-permit-indexed-collection-as-map-key