Create objects
The examples on this page demonstrate how to create individual objects in Weaviate.
For creating multiple objects at once, see How-to: Batch Import.
Create an object
This example creates an object in the JeopardyQuestion
collection.
- Python Client v4
- Python Client v3
- JS/TS Client v3
- JS/TS Client v2
- Java
- Go
jeopardy = client.collections.get("JeopardyQuestion")
uuid = jeopardy.data.insert({
"question": "This vector DB is OSS & supports automatic property type inference on import",
# "answer": "Weaviate", # properties can be omitted
"newProperty": 123, # will be automatically added as a number property
})
print(uuid) # the return value is the object's UUID
uuid = client.data_object.create(
class_name="JeopardyQuestion",
data_object={
"question": "This vector DB is OSS & supports automatic property type inference on import",
# "answer": "Weaviate", # schema properties can be omitted
"newProperty": 123, # will be automatically added as a number property
}
)
print(uuid) # the return value is the object's UUID
const jeopardy = client.collections.get('JeopardyQuestion')
uuid = await jeopardy.data.insert({
'question': 'This vector DB is OSS & supports automatic property type inference on import',
// 'answer': 'Weaviate', // properties can be omitted
'newProperty': 123, // will be automatically added as a number property
})
console.log('UUID: ', 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
newProperty: 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(className)
.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("newProperty", 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
"newProperty": 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))
Additional information
To create an object, specify the following:
- The object data you want to add
- The target collection
- If multi-tenancy is enabled, specify the tenant
By default, auto-schema creates new collections and adds new properties.
Create an object with a specified vector
When you create an object, you can provide a vector. (For specifying multiple, named vectors, see below.)
- Python Client v4
- Python Client v3
- JS/TS Client v3
- JS/TS Client v2
- Java
- Go
jeopardy = client.collections.get("JeopardyQuestion")
uuid = jeopardy.data.insert(
properties={
"question": "This vector DB is OSS and supports automatic property type inference on import",
"answer": "Weaviate",
},
vector=[0.12345] * 1536
)
print(uuid) # the return value is the object's UUID
uuid = client.data_object.create(
class_name="JeopardyQuestion",
data_object={
"question": "This vector DB is OSS and supports automatic property type inference on import",
"answer": "Weaviate",
},
vector=[0.12345] * 1536
)
print(uuid) # the return value is the object's UUID
const jeopardy = client.collections.get('JeopardyQuestion')
uuid = await jeopardy.data.insert({
properties: {
'question': 'This vector DB is OSS & supports automatic property type inference on import',
// 'answer': 'Weaviate', // properties can be omitted
'newProperty': 123, // will be automatically added as a number property
},
vectors: Array(1536).fill(0.12345)
})
console.log('UUID: ', 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',
})
.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(className)
.withProperties(new HashMap<String, Object>() {{
put("question", "This vector DB is OSS and supports automatic property type inference on import");
put("answer", "Weaviate");
}})
.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",
}).
WithVector(vector).
Do(ctx)
// the returned value is a wrapped object
b, err := json.MarshalIndent(w.Object, "", " ")
// CreateObjectWithId END
require.NoError(t, err)
fmt.Println(string(b))
// CreateObjectWithId END
})
t.Run("create object with id and vector", func(t *testing.T) {
// CreateObjectWithId START
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").
Do(ctx)
// CreateObjectWithId END
require.NoError(t, err)
// CreateObjectWithId START
// the returned value is a wrapped object
b, err := json.MarshalIndent(w.Object, "", " ")
// CreateObjectWithId END
require.NoError(t, err)
// CreateObjectWithId START
fmt.Println(string(b))
// CreateObjectWithId END
})
t.Run("create object with deterministic id", func(t *testing.T) {
// CreateObjectWithDeterministicIdTODO START
properties := map[string]interface{}{
"question": "This vector DB is OSS and supports automatic property type inference on import",
"answer": "Weaviate",
}
// String id = "gen_uuid5(properties)"; // TODO implement
id := "17f91943-1a5e-46d3-9323-a1cdb735591c"
w, err := client.Data().Creator().
WithClassName("JeopardyQuestion").
WithProperties(properties).
WithID(id).
Do(ctx)
// CreateObjectWithDeterministicIdTODO END
require.NoError(t, err)
// CreateObjectWithDeterministicIdTODO START
// the returned value is a wrapped object
b, err := json.MarshalIndent(w.Object, "", " ")
// CreateObjectWithDeterministicIdTODO END
require.NoError(t, err)
// CreateObjectWithDeterministicIdTODO START
fmt.Println(string(b))
// CreateObjectWithDeterministicIdTODO END
})
t.Run("validate object", func(t *testing.T) {
// ValidateObject START
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)
// ValidateObject END
require.Error(t, err)
// ValidateObject START
assert.ErrorContains(t, err, "invalid object: no such prop with name 'thisPropShouldNotEndUpInTheSchema' found")
// ValidateObject END
})
}
Create an object with named vectors
v1.24
When you create an object, you can specify named vectors (if configured in your collection).
- Python Client v4
- Python Client v3
- JS/TS Client v3
- JS/TS Client v2
reviews = client.collections.get("WineReviewNV") # This collection must have named vectors configured
uuid = reviews.data.insert(
properties={
"title": "A delicious Riesling",
"review_body": "This wine is a delicious Riesling which pairs well with seafood.",
"country": "Germany",
},
# Specify the named vectors, following the collection definition
vector={
"title": [0.12345] * 1536,
"review_body": [0.31313] * 1536,
"title_country": [0.05050] * 1536,
}
)
print(uuid) # the return value is the object's UUID
# Unfortunately, named vectors are not suppored in the v3 API / Python client.
# Please upgrade to the v4 API / Python client to use named vectors.
const reviews = client.collections.get('WineReviewNV')
uuid = await reviews.data.insert({
properties: {
'title': 'A delicious Riesling',
'review_body': 'This wine is a delicious Riesling which pairs well with seafood.',
'country': 'Germany',
},
vectors: {
title: Array(1536).fill(0.12345),
review_body: Array(1536).fill(0.31313),
title_country: Array(1536).fill(0.05050),
}
})
console.log('UUID: ', uuid)
result = await client.data
.creator()
.withClassName('WineReviewNV')
.withProperties({
title: 'A delicious Riesling',
review_body: 'This wine is a delicious Riesling which pairs well with seafood.',
country: 'Germany',
})
// Specify the named vectors, following the collection definition
.withVectors({
title: Array(1536).fill(0.12345),
review_body: Array(1536).fill(0.31313),
title_country: Array(1536).fill(0.05050),
})
.do();
console.log(JSON.stringify(result, null, 2)); // the returned value is the object
Create an object with a specified ID
When you create an object, you can specify an ID.
If no ID is provided, Weaviate will generate a random UUID.
- Python Client v4
- Python Client v3
- JS/TS Client v3
- JS/TS Client v2
- Java
- Go
properties = {
"question": "This vector DB is OSS and supports automatic property type inference on import",
"answer": "Weaviate",
}
jeopardy = client.collections.get("JeopardyQuestion")
uuid = jeopardy.data.insert(
properties=properties,
uuid="12345678-e64f-5d94-90db-c8cfa3fc1234"
)
print(uuid) # the return value is the object's UUID
uuid = client.data_object.create(
class_name="JeopardyQuestion",
data_object={
"question": "This vector DB is OSS and supports automatic property type inference on import",
"answer": "Weaviate",
},
uuid="12345678-e64f-5d94-90db-c8cfa3fc1234"
)
print(uuid) # the return value is the object's UUID
const jeopardy = client.collections.get('JeopardyQuestion')
uuid = await jeopardy.data.insert({
properties: {
'question': 'This vector DB is OSS and supports automatic property type inference on import',
'answer': 'Weaviate',
},
id: '12345678-e64f-5d94-90db-c8cfa3fc1234'
})
console.log('UUID: ', 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')
.do();
console.log(JSON.stringify(result, null, 2)); // the returned value is the object
Result<WeaviateObject> result = client.data().creator()
.withClassName(className)
.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")
.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").
Do(ctx)
// the returned value is a wrapped object
b, err := json.MarshalIndent(w.Object, "", " ")
fmt.Println(string(b))
Generate deterministic IDs
You can generate an ID based on your data object.
Object IDs are not randomly generated. The same value always generates the same ID.
Weaviate throws an error if you provide a duplicate ID. Use deterministic IDs to avoid inserting duplicate objects.
- Python Client v4
- Python Client v3
- JS/TS Client v3
- JS/TS Client v2
- 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",
}
jeopardy = client.collections.get("JeopardyQuestion")
uuid = jeopardy.data.insert(
properties=data_object,
uuid=generate_uuid5(data_object),
)
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(
class_name="JeopardyQuestion",
data_object=data_object,
uuid=generate_uuid5(data_object),
)
import { generateUuid5 } from 'weaviate-client';
const jeopardy = client.collections.get('JeopardyQuestion')
const dataObject = {
'question': 'This vector DB is OSS and supports automatic property type inference on import',
'answer': 'Weaviate',
}
uuid = await jeopardy.data.insert({
properties: dataObject,
id: generateUuid5('Article', JSON.stringify(dataObject)) // use the whole object to generate a uuid
// id: generateUuid5(dataObject.answer) // use a specific property to generate a uuid
})
console.log('UUID: ', uuid)
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
Additional information
generate_uuid5
(Python)generateUuid5
(TypeScript)
Create an object with cross-references
You can create an object with cross-references to other objects.
- Python Client v4
- Python Client v3
- JS/TS Client v3
- JS/TS Client v2
questions = client.collections.get("JeopardyQuestion")
questions.data.insert(
properties=properties, # A dictionary with the properties of the object
uuid=obj_uuid, # The UUID of the object
references={"hasCategory": category_uuid}, # e.g. {"hasCategory": "583876f3-e293-5b5b-9839-03f455f14575"}
)
# data_obj is a dictionary with the object's properties
data_obj["hasCategory"] = [ # Add one or more cross-references through the "hasCategory" property
{"beacon": f"weaviate://localhost/JeopardyCategory/{category_uuid}"}
]
data_uuid = client.data_object.create(
data_obj,
"JeopardyQuestion",
)
const category = client.collections.get('JeopardyCategory')
const dataObject = {'name': 'Science'}
const response = await category.data.insert({
properties: dataObject,
references: {
'hasCategory': categoryId // e.g. {'hasCategory': '583876f3-e293-5b5b-9839-03f455f14575'}
}
})
console.log('UUID: ', response)
response = await client.data
.creator()
.withClassName('JeopardyQuestion')
.withId('f7344d30-7fe4-54dd-a233-fcccd4379d5c')
.withProperties({
'question': 'What tooling helps make Weaviate scalable?',
'answer': 'Sharding, multi-tenancy, and replication',
'hasCategory': [{ // Specify one or more cross-references
'beacon': 'weaviate://localhost/583876f3-e293-5b5b-9839-03f455f14575',
}],
})
.do();
console.log(JSON.stringify(response, null, 2));
See How-to: Cross-references for more on working with cross-references.
Create an object with geoCoordinates
Currently, geo-coordinate filtering is limited to the nearest 800 results from the source location, which will be further reduced by any other filter conditions and search parameters.
If you plan on a densely populated dataset, consider using another strategy such as geo-hashing into a text
datatype, and filtering further, such as with a ContainsAny
filter.
If you want to supply a geoCoordinates
property, you need to specify the latitude
and longitude
as floating point decimal degrees:
- Python Client v4
- Python Client v3
- JS/TS Client v3
- JS/TS Client v2
- Go
- Java
publications = client.collections.get("Publication")
publications.data.insert(
properties={
"headquartersGeoLocation": {
"latitude": 52.3932696,
"longitude": 4.8374263
}
},
)
data_obj = {
"name": "Elsevier",
"headquartersGeoLocation": {
"latitude": 52.3932696,
"longitude": 4.8374263
}
}
data_uuid = client.data_object.create(
data_obj,
"Publication",
uuid="df48b9f6-ba48-470c-bf6a-57657cb07390", # optional, if not provided, one is going to be generated
)
const publication = client.collections.get('Publication')
uuid = await publication.data.insert({
properties: {
name: 'Elsevier',
headquartersGeoLocation: {
'latitude': 52.3932696,
'longitude': 4.8374263,
},
},
id: 'df48b9f6-ba48-470c-bf6a-57657cb07390'
})
console.log('UUID: ', uuid)
const response = await client.data
.creator()
.withClassName('Publication')
.withId('df48b9f6-ba48-470c-bf6a-57657cb07390')
.withProperties({
'name': 'Elsevier',
'headquartersGeoLocation': {
'latitude': 52.3932696,
'longitude': 4.8374263,
},
})
.do();
console.log(JSON.stringify(response, null, 2));
package main
import (
"context"
"fmt"
"github.com/weaviate/weaviate-go-client/v4/weaviate"
)
func main() {
cfg := weaviate.Config{
Host: "localhost:8080",
Scheme: "http",
}
client, err := weaviate.NewClient(cfg)
if err != nil {
panic(err)
}
dataSchema := map[string]interface{}{
"name": "Elsevier",
"headquartersGeoLocation": map[string]float32{
"latitude": 52.3932696,
"longitude": 4.8374263,
},
}
created, err := client.Data().Creator().
WithClassName("Publication").
WithID("df48b9f6-ba48-470c-bf6a-57657cb07390").
WithProperties(dataSchema).
Do(context.Background())
if err != nil {
panic(err)
}
fmt.Printf("%v", created)
}
package io.weaviate;
import java.util.HashMap;
import java.util.Map;
import io.weaviate.client.Config;
import io.weaviate.client.WeaviateClient;
import io.weaviate.client.base.Result;
import io.weaviate.client.v1.data.model.WeaviateObject;
public class App {
public static void main(String[] args) {
Config config = new Config("http", "localhost:8080");
WeaviateClient client = new WeaviateClient(config);
Map<String, Object> dataSchema = new HashMap<>();
dataSchema.put("name", "Elsevier");
dataSchema.put("headquartersGeoLocation", new HashMap() { {
put("latitude", 52.3932696f);
put("longitude", 4.8374263f);
} });
Result<WeaviateObject> result = client.data().creator()
.withClassName("Publication")
.withID("df48b9f6-ba48-470c-bf6a-57657cb07390")
.withProperties(dataSchema)
.run();
if (result.hasErrors()) {
System.out.println(result.getError());
return;
}
System.out.println(result.getResult());
}
}
Validate objects before creation
Before you create an object, you can validate it against the collection definition.
- Python Client v4
- Python Client v3
- JS/TS Client v3
- JS/TS Client v2
- Java
- Go
# Validate is currently not supported with the Weaviate Python client v4
result = client.data_object.validate(
class_name="JeopardyQuestion",
data_object={
"question": "This vector DB is open-source and supports auto-schema",
"answer": "Weaviate",
"thisPropShouldNotEndUpInTheSchema": -1,
},
uuid="12345678-1234-1234-1234-123456789012",
)
# "invalid object: no such prop with name "thisPropShouldNotEndUpInTheSchema" found..."
print(json.dumps(result, indent=2))
// Validate is currently not supported with the Weaviate TypeScript client v3
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(className)
.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")
Multiple vectors (named vectors)
Weaviate collections support multiple named vectors.
Collections can have multiple named vectors.
The vectors in a collection can have their own configurations. Each vector space can set its own index, its own compression algorithm, and its own vectorizer. This means you can use different vectorization models, and apply different distance metrics, to the same object.
To work with named vectors, adjust your queries to specify a target vector for vector search or hybrid search queries.
Related pages
Questions and feedback
If you have any questions or feedback, let us know in the user forum.