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.
If a snippet doesn't work or you have feedback, please open a GitHub issue.
jeopardy = client.collections.use("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
const jeopardy = client.collections.use('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)
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))
questions := client.Collections.Use("JeopardyQuestion")
res, err := questions.Data.Insert(ctx, &data.Object{
Properties: map[string]any{
"question": "This vector DB is OSS & supports automatic property type inference on import",
// "answer": "Weaviate", // Properties can be omitted.
"newProperty": 123, // Auto-schema adds this as a number property.
},
})
if err != nil {
// handle error
panic(err)
}
fmt.Println(res.UUIDs[0]) // The id of the new object.
var jeopardy = client.collections.use("JeopardyQuestion");
var uuid = jeopardy.data.insert(Map.of(
"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
)).uuid();
System.out.println(uuid); // the return value is the object's UUID
var jeopardy = client.Collections.Use("JeopardyQuestion");
var uuid = await jeopardy.Data.Insert(
new
{
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.WriteLine(uuid); // the return value is the object's UUID
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.)
If a snippet doesn't work or you have feedback, please open a GitHub issue.
jeopardy = client.collections.use("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
const jeopardy = client.collections.use('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)
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
})
}
questions := client.Collections.Use("JeopardyQuestion")
res, err := questions.Data.Insert(ctx, &data.Object{
Properties: map[string]any{
"question": "This vector DB is OSS and supports automatic property type inference on import",
"answer": "Weaviate",
},
Vectors: []types.Vector{
{Name: "default", Single: []float32{0.12345, 0.6789, 0.9876}},
},
})
if err != nil {
// handle error
panic(err)
}
fmt.Println(res.UUIDs[0]) // The id of the new object.
var jeopardy = client.collections.use("JeopardyQuestion");
var uuid = jeopardy.data.insert(Map.of("question",
"This vector DB is OSS and supports automatic property type inference on import",
"answer", "Weaviate"),
meta -> meta.vectors(Vectors.of(new float[384])) // Using a zero vector for demonstration
).uuid();
System.out.println(uuid); // the return value is the object's UUID
var jeopardy = client.Collections.Use("JeopardyQuestion");
var uuid = await jeopardy.Data.Insert(
new
{
question = "This vector DB is OSS and supports automatic property type inference on import",
answer = "Weaviate",
},
vectors: new float[300] // Using a zero vector for demonstration
);
Console.WriteLine(uuid); // the return value is the object's UUID
Create an object with named vectors
When you create an object, you can specify named vectors (if configured in your collection).
If a snippet doesn't work or you have feedback, please open a GitHub issue.
reviews = client.collections.use("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
const reviews = client.collections.use('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)
var reviews = client.collections.use("WineReviewNV"); // This collection must have named vectors configured
var uuid = reviews.data.insert(
Map.of("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
meta -> meta.vectors(Vectors.of("title", new float[1536]),
Vectors.of("review_body", new float[1536]),
Vectors.of("title_country", new float[1536]))
).uuid();
System.out.println(uuid); // the return value is the object's UUID
var reviews = client.Collections.Use("WineReviewNV"); // This collection must have named vectors configured
var uuid = await reviews.Data.Insert(
new
{
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
vectors: new Vectors
{
{ "title", new float[1536] },
{ "review_body", new float[1536] },
{ "title_country", new float[1536] },
}
);
Console.WriteLine(uuid); // the return value is the object's UUID
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.
If a snippet doesn't work or you have feedback, please open a GitHub issue.
properties = {
"question": "This vector DB is OSS and supports automatic property type inference on import",
"answer": "Weaviate",
}
jeopardy = client.collections.use("JeopardyQuestion")
uuid = jeopardy.data.insert(
properties=properties,
uuid="12345678-e64f-5d94-90db-c8cfa3fc1234"
)
print(uuid) # the return value is the object's UUID
const jeopardy = client.collections.use('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)
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))
questions := client.Collections.Use("JeopardyQuestion")
id := uuid.MustParse("12345678-e64f-5d94-90db-c8cfa3fc1234")
res, err := questions.Data.Insert(ctx, &data.Object{
UUID: &id,
Properties: map[string]any{
"question": "This vector DB is OSS and supports automatic property type inference on import",
"answer": "Weaviate",
},
})
if err != nil {
// handle error
panic(err)
}
fmt.Println(res.UUIDs[0]) // The id of the new object.
Map<String, Object> properties = new HashMap<>();
properties.put("question",
"This vector DB is OSS and supports automatic property type inference on import");
properties.put("answer", "Weaviate");
var jeopardy = client.collections.use("JeopardyQuestion");
var uuid = jeopardy.data.insert(properties,
meta -> meta.uuid("12345678-e64f-5d94-90db-c8cfa3fc1234")
).uuid();
System.out.println(uuid); // the return value is the object's UUID
var jeopardy = client.Collections.Use("JeopardyQuestion");
var uuid = await jeopardy.Data.Insert(
new
{
question = "This vector DB is OSS and supports automatic property type inference on import",
answer = "Weaviate",
},
uuid: Guid.Parse("12345678-e64f-5d94-90db-c8cfa3fc1234")
);
Console.WriteLine(uuid); // the return value is the object's UUID
Generate deterministic IDs
You can generate an ID based on your data object.
A deterministic ID is not random: the same object value always generates the same ID.
Weaviate throws an error if you provide a duplicate ID. Use deterministic IDs to avoid inserting duplicate objects.
If a snippet doesn't work or you have feedback, please open a GitHub issue.
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.use("JeopardyQuestion")
uuid = jeopardy.data.insert(
properties=data_object,
uuid=generate_uuid5(data_object),
)
import { generateUuid5 } from '@weaviate/node';
const jeopardy = client.collections.use('JeopardyQuestion')
const dataObject = {
'question': 'This vector DB is OSS and supports automatic property type inference on import',
'answer': 'Weaviate',
}
const newUuid = generateUuid5('Article', JSON.stringify(dataObject)) // use the whole object to generate a uuid
uuid = await jeopardy.data.insert({
properties: dataObject,
id: newUuid
// id: generateUuid5(dataObject.answer) // use a specific property to generate a uuid
})
console.log('UUID: ', uuid)
// This feature is under development
// Coming soon
// In Java, you can generate a deterministic UUID from a string or bytes.
// This helper function uses UUID.nameUUIDFromBytes for this purpose.
Map<String, Object> dataObject = new HashMap<>();
dataObject.put("question",
"This vector DB is OSS and supports automatic property type inference on import");
dataObject.put("answer", "Weaviate");
var jeopardy = client.collections.use("JeopardyQuestion");
var uuid = jeopardy.data.insert(dataObject,
meta -> meta.uuid(generateUuid5(dataObject.toString()).toString())
).uuid();
// In C#, you can generate a deterministic UUID from a string or bytes.
// This helper function creates a UUID v5 for this purpose.
var dataObject = new
{
question = "This vector DB is OSS and supports automatic property type inference on import",
answer = "Weaviate",
};
var dataObjectString = JsonSerializer.Serialize(dataObject);
var jeopardy = client.Collections.Use("JeopardyQuestion");
var uuid = await jeopardy.Data.Insert(
dataObject,
uuid: GenerateUuid5(dataObjectString)
);
Additional information
To generate deterministic IDs, use one of these methods:
generate_uuid5(Python)generateUuid5(TypeScript)
Create an object with cross-references
Queries involving cross-references can be slower than queries that do not involve cross-references, especially at scale such as for multiple objects or complex queries.
At the first instance, we strongly encourage you to consider whether you can avoid using cross-references in your data schema. As a scalable AI database, Weaviate is well-placed to perform complex queries with vector, keyword and hybrid searches involving filters. You may benefit from rethinking your data schema to avoid cross-references where possible.
For example, instead of creating separate "Author" and "Book" collections with cross-references, consider embedding author information directly in Book objects and using searches and filters to find books by author characteristics.
You can create an object with cross-references to other objects.
If a snippet doesn't work or you have feedback, please open a GitHub issue.
questions = client.collections.use("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"}
)
const category = client.collections.use('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)
var questions = client.collections.use("JeopardyQuestion");
var result = questions.data.insert(properties, // A map with the properties of the object
opt -> opt
.reference("hasCategory", ObjectReference.uuids(categoryUuid)) // e.g. {"hasCategory":
// "583876f3-e293-5b5b-9839-03f455f14575"}
);
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:
If a snippet doesn't work or you have feedback, please open a GitHub issue.
publications = client.collections.use("Publication")
publications.data.insert(
properties={
"headquartersGeoLocation": {
"latitude": 52.3932696,
"longitude": 4.8374263
}
},
)
const publication = client.collections.use('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)
package main
import (
"context"
"fmt"
"github.com/weaviate/weaviate-go-client/v5/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)
}
var publications = client.collections.use("Publication");
var uuid = publications.data
.insert(Map.of("headquartersGeoLocation",
Map.of("latitude", 52.3932696, "longitude", 4.8374263)))
.uuid();
var publications = client.Collections.Use("Publication");
var uuid = await publications.Data.Insert(
new { headquartersGeoLocation = new GeoCoordinate(52.3932696f, 4.8374263f) }
);
Validate objects before creation
Before you create an object, you can validate it against the collection definition.
If a snippet doesn't work or you have feedback, please open a GitHub issue.
# Validate is currently not supported with the Weaviate Python client v4
// Validate is currently not supported with the Weaviate TypeScript client v3
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")
// Coming soon
// Coming soon
// Coming soon
Multiple vector embeddings (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
Have a question or feedback? Here's how to reach us.
