OrientDB 2.2设置属性默认值为JSON字符串遇解析问题求助
Hey there! I’ve run into exactly this problem with OrientDB 2.2 before—super frustrating when the database auto-parses your JSON string default into an embedded object instead of keeping it as a raw string. Let’s break down why this happens and how to fix it.
Why This Happens
OrientDB has an automatic JSON parsing feature: if it detects that a string value matches valid JSON syntax, it will automatically convert it into an embedded document/object, even if you’ve explicitly set the property type to STRING. That’s why your schema looks correct initially, but inserts end up with parsed objects instead of raw strings.
Step-by-Step Solution
1. Define the Property with Properly Escaped Default Value
When creating the property, you need to escape the inner quotes in your JSON string so OrientDB treats the entire value as a raw string, not a JSON object. Use backslashes to escape double quotes inside the default value string.
Here’s the correct SQL command:
CREATE CLASS Person EXTENDS V; CREATE PROPERTY Person._template STRING DEFAULT '{\\"name\\":\\"default\\",\\"age\\":30}';
2. Update Existing Properties (If Needed)
If you already created the _template property and need to fix its default value, use the ALTER PROPERTY command with the same escaped string:
ALTER PROPERTY Person._template DEFAULT '{\\"name\\":\\"default\\",\\"age\\":30}';
3. Verify the Fix
After setting up the property correctly:
- Check the schema with
SELECT * FROM metadata:schema WHERE name = 'Person'—you’ll see the default value is stored as the raw escaped string. - Insert a new record with
INSERT INTO Person SET name = 'John'(no need to set_templateexplicitly). - Run your query
select _template from Person—the result will now be the raw JSON string, not a parsed object.
Alternative: Use Single Quotes Inside JSON
If escaping backslashes feels cumbersome, you can use single quotes for the JSON key/value pairs instead, then wrap the entire string in double quotes:
CREATE PROPERTY Person._template STRING DEFAULT '{"name":"default","age":30}';
This also prevents OrientDB from auto-parsing the string into an object, and works if your application can handle single-quoted JSON (or you can normalize the quotes later in your code).
内容的提问来源于stack exchange,提问作者Joshua Stillerman

