Create objects
Overview
This page shows you how to create individual objects in Weaviate.
Requirements
To create an object, specify:
- The object data to be added, and
- The target class.
For classes where multi-tenancy is enabled, you will also need to specify the tenant name when creating objects. See Manage data: multi-tenancy operations for details on how.
Object data vs class definition
Compared to the class definition, the object data:
- Can omit defined properties.
- Can include new properties.
Any new properties will be added to the class definition during object creation with auto-schema.
Example
This example shows how to create an object in the JeopardyQuestion
class, with:
- An existing property (
question
), - A new property (
somePropNotInTheSchema
), and - Omits an existing property (
answer
).
- Python
- JavaScript/TypeScript
- Java
- Go
uuid = client.data_object.create({
'question': 'This vector DB is OSS & supports automatic property type inference on import',
# 'answer': 'Weaviate', # schema properties can be omitted
'somePropNotInTheSchema': 123, # will be automatically added as a number property
}, 'JeopardyQuestion')
print(uuid) # the return value is the object's UUID
result = await client.data
.creator()
.withClassName('JeopardyQuestion')
.withProperties({
question: 'This vector DB is OSS and supports automatic property type inference on import',
// answer: 'Weaviate', // schema properties can be omitted
somePropNotInTheSchema: 123, // will be automatically added as a number property
})
.do();
console.log(JSON.stringify(result, null, 2)); // the returned value is the object
Result<WeaviateObject> result = client.data().creator()
.withClassName("JeopardyQuestion")
.withProperties(new HashMap<String, Object>() {{
put("question", "This vector DB is OSS and supports automatic property type inference on import");
// put("answer", "Weaviate"); // schema properties can be omitted
put("somePropNotInTheSchema", 123); // will be automatically added as a number property
}})
.run();
// the returned value is the object
String json = new GsonBuilder().setPrettyPrinting().create().toJson(result.getResult());
System.out.println(json);
w, err := client.Data().Creator().
WithClassName("JeopardyQuestion").
WithProperties(map[string]interface{}{
"question": "This vector DB is OSS and supports automatic property type inference on import",
// "answer": "Weaviate", // schema properties can be omitted
"somePropNotInTheSchema": 123, // will be automatically added as a number property
}).
Do(ctx)
// the returned value is a wrapped object
b, err := json.MarshalIndent(w.Object, "", " ")
fmt.Println(string(b))
Optional parameters
Optionally, you can specify an id or a vector.
id
You can optionally specify an ID in UUID format. Otherwise, Weaviate will generate a random UUID.
vector
You can optionally specify a vector to represent each object. Otherwise, Weaviate will follow the relevant vectorizer setting.
Example
- Python
- JavaScript/TypeScript
- Java
- Go
uuid = client.data_object.create(
data_object={
'question': 'This vector DB is OSS and supports automatic property type inference on import',
'answer': 'Weaviate',
},
class_name='JeopardyQuestion',
uuid='12345678-e64f-5d94-90db-c8cfa3fc1234',
vector=[0.12345] * 1536
)
print(uuid) # the return value is the object's UUID
result = await client.data
.creator()
.withClassName('JeopardyQuestion')
.withProperties({
question: 'This vector DB is OSS and supports automatic property type inference on import',
answer: 'Weaviate',
})
.withId('12345678-e64f-5d94-90db-c8cfa3fc1234')
.withVector(Array(1536).fill(0.12345))
.do();
console.log(JSON.stringify(result, null, 2)); // the returned value is the object
Result<WeaviateObject> result = client.data().creator()
.withClassName("JeopardyQuestion")
.withProperties(new HashMap<String, Object>() {{
put("question", "This vector DB is OSS and supports automatic property type inference on import");
put("answer", "Weaviate");
}})
.withID("12345678-e64f-5d94-90db-c8cfa3fc1234")
.withVector(Collections.nCopies(1536, 0.12345f).toArray(new Float[0]))
.run();
// the returned value is the object
String json = new GsonBuilder().setPrettyPrinting().create().toJson(result.getResult());
System.out.println(json);
vector := make([]float32, 1536)
for i := 0; i < len(vector); i++ {
vector[i] = 0.12345
}
w, err := client.Data().Creator().
WithClassName("JeopardyQuestion").
WithProperties(map[string]interface{}{
"question": "This vector DB is OSS and supports automatic property type inference on import",
"answer": "Weaviate",
}).
WithID("12345678-e64f-5d94-90db-c8cfa3fc1234").
WithVector(vector).
Do(ctx)
// the returned value is a wrapped object
b, err := json.MarshalIndent(w.Object, "", " ")
fmt.Println(string(b))
Preventing duplicates
In Weaviate, the only unique field is the id
. If you try to create an object with an existing id, Weaviate will throw an error. (In batch imports, Weaviate will overwrite the object if one exists.)
To prevent duplicates, we suggest:
- Using a deterministic ID generation method, and
- Checking if an object exists before creating it.
Generate deterministic ID
You can do so with the generate_uuid5
function in the Python client, or the generateUuid5
function in the TypeScript client.
Example
- Python
- JavaScript/TypeScript
- Java
- Go
from weaviate.util import generate_uuid5 # Generate a deterministic ID
data_object = {
'question': 'This vector DB is OSS and supports automatic property type inference on import',
'answer': 'Weaviate',
}
uuid = client.data_object.create(
data_object=data_object,
class_name='JeopardyQuestion',
uuid=generate_uuid5(data_object),
)
import { generateUuid5 } from 'weaviate-ts-client'; // requires v1.3.2+
const dataObj = {
question: 'This vector DB is OSS and supports automatic property type inference on import',
answer: 'Weaviate'
}
result = await client.data
.creator()
.withClassName('JeopardyQuestion')
.withProperties(dataObj)
.withId(generateUuid5(JSON.stringify(dataObj)))
.do();
console.log(JSON.stringify(result, null, 2)); // the returned value is the object
// This feature is under development
// This feature is under development
Check if an object exists
You can check if an object exists given its id.
Validating before creation
You can validate an object against the class definition before creating it.
This will confirm:
- Whether the creation of an object will succeed, and
- That it doesn't have any extra properties vs. the schema.
- Python
- JavaScript/TypeScript
- Java
- Go
result = client.data_object.validate(
data_object={
'question': 'This vector DB is open-source and supports auto-schema',
'answer': 'Weaviate',
'thisPropShouldNotEndUpInTheSchema': -1,
},
class_name='JeopardyQuestion',
uuid='12345678-1234-1234-1234-123456789012',
)
# "invalid object: no such prop with name 'thisPropShouldNotEndUpInTheSchema' found..."
print(json.dumps(result, indent=2))
try {
await client.data
.validator()
.withClassName('JeopardyQuestion')
.withId('12345678-1234-1234-1234-123456789012') // placeholder in UUID format (required)
.withProperties({
question: 'This vector DB is open-source and supports auto-schema',
answer: 'Weaviate',
thisPropShouldNotEndUpInTheSchema: -1,
})
.do();
} catch (e) {
// "invalid object: no such prop with name 'thisPropShouldNotEndUpInTheSchema' found..."
console.error('Expecting error about thisPropShouldNotEndUpInTheSchema:', e.message);
}
Result<Boolean> result = client.data()
.validator()
.withClassName("JeopardyQuestion")
.withProperties(new HashMap<String, Object>() {{
put("question", "This vector DB is OSS and supports automatic property type inference on import");
put("answer", "Weaviate");
put("thisPropShouldNotEndUpInTheSchema", -1);
}})
.withID("12345678-1234-1234-1234-123456789012")
.run();
assertThat(result.getResult()).isFalse();
assertThat(result.hasErrors()).isTrue();
assertThat(result.getError().getMessages().get(0).getMessage())
.contains("invalid object: no such prop with name 'thisPropShouldNotEndUpInTheSchema' found");
err := client.Data().Validator().
WithClassName("JeopardyQuestion").
WithProperties(map[string]interface{}{
"question": "This vector DB is OSS and supports automatic property type inference on import",
"answer": "Weaviate",
"thisPropShouldNotEndUpInTheSchema": -1,
}).
WithID("12345678-1234-1234-1234-123456789012").
Do(ctx)
assert.ErrorContains(t, err, "invalid object: no such prop with name 'thisPropShouldNotEndUpInTheSchema' found")
More Resources
For additional information, try these sources.