Neo4j Cypher数据类型定义方法及属性类型确认咨询
Great question! Cypher (the query language for Neo4j, which I assume you're referring to as CQL here) handles data types a bit differently from SQL, so it’s totally reasonable to wonder about this. Let’s break it down clearly:
First, Your Specific Example: Age:23
When you run CREATE (a:User {UserName:'Jack', Age:23}), the Age property is automatically inferred as an Integer type. Cypher uses dynamic typing, meaning it guesses the type directly from the literal value you provide:
- Whole numbers without a decimal point (like
23) default toInteger - Numbers with a decimal point (like
23.0or1.75) becomeFloat
Common Cypher Data Types (and How to Use Them)
Unlike SQL, you don’t need to declare types upfront when creating nodes or relationships, but here’s a breakdown of the key types you’ll encounter, with practical examples:
- Integer: Whole numbers (positive or negative). Example:
Age:23,Points:-50 - Float: Floating-point numbers for non-integer values. Example:
Height:1.80,Temperature:22.5 - String: Text values wrapped in single or double quotes. Example:
UserName:'Jack',Bio:"Loves hiking and coding" - Boolean: True/false values. Example:
IsActive:true,HasPremium:false - Decimal: For precise decimal calculations (perfect for currency). You need to explicitly use the
decimal()function to create these. Example:Price:decimal('49.99') - List: Ordered collections of values (you can mix types, but keeping them consistent is best practice). Example:
Hobbies:['reading', 'gaming'],Scores:[95, 88, 92] - Map: Nested key-value pairs. Example:
Profile:{City:'Paris', Job:'Designer'} - Date/Time Types: For temporal data, use dedicated functions:
- Date:
JoinDate:date('2024-01-15') - Datetime:
LastLogin:datetime('2024-01-15T14:30:00') - Local time:
WakeUpTime:localtime('07:00:00')
- Date:
Explicitly Setting or Converting Types
If you need to override automatic inference (e.g., store a whole number as a Float, or ensure a precise Decimal), use conversion functions:
- Convert to Float:
Age:toFloat(23) - Convert to Decimal:
Price:decimal('23') - Convert to String:
UserId:toString(12345)
Enforcing Type Consistency
If you want strict type rules like SQL, you can create a constraint to force a property to always use a specific type. For example, to ensure all User nodes’ Age is an Integer:
CREATE CONSTRAINT ON (u:User) ASSERT u.Age IS INTEGER
This will throw an error if anyone tries to set Age to a Float or String later.
内容的提问来源于stack exchange,提问作者Pantea

