Object-level queries (Get)
This page covers object-level query functions. They are collectively referred to as Get
queries within.
Parameters
A Get
query requires the target collection to be specified.
-
In GraphQL calls, the properties to be retrieved to be must be specified explicitly.
-
In gRPC calls, all properties are fetched by default.
-
Metadata retrieval is optional in both GraphQL and gRPC calls.
Available arguments
Each Get
query can include any of the following types of arguments:
Argument | Description | Required |
---|---|---|
Collection | Also called "class". The object collection to be retrieved from. | Yes |
Properties | Properties to be retrieved | Yes (GraphQL) (No if using gRPC API) |
Cross-references | Cross-references to be retrieved | No |
Metadata | Metadata (additional properties) to be retrieved | No |
Conditional filters | Filter the objects to be retrieved | No |
Search operators | Specify the search strategy (e.g. near text, hybrid, bm25) | No |
Additional operators | Specify additional operators (e.g. limit, offset, sort) | No |
Tenant name | Specify the tenant name | Yes, if multi-tenancy enabled. (Read more: what is multi-tenancy?) |
Consistency level | Specify the consistency level | No |
Example usage
- Python Client v4
- Python Client v3
- JS/TS Client v2
- Go
- Java
- Curl
- GraphQL
import weaviate
import weaviate.classes as wvc
import os
client = weaviate.connect_to_local()
try:
collection = client.collections.get("JeopardyQuestion")
response = collection.query.fetch_objects()
for o in response.objects:
print(o.properties) # Inspect returned objects
finally:
client.close()
import weaviate
client = weaviate.Client(
"https://WEAVIATE_INSTANCE_URL", # Replace with your Weaviate URL
)
result = client.query.get("JeopardyQuestion", ["question", "answer", "points"]).do()
print(result)
import weaviate from 'weaviate-ts-client';
const client = weaviate.client({
scheme: 'https',
host: 'WEAVIATE_INSTANCE_URL', // Replace with your Weaviate URL
});
const response = await client.graphql
.get()
.withClassName('JeopardyQuestion')
.withFields('question answer points')
.do();
console.log(response);
package main
import (
"context"
"fmt"
"github.com/weaviate/weaviate-go-client/v5/weaviate"
"github.com/weaviate/weaviate-go-client/v5/weaviate/graphql"
)
func main() {
cfg := weaviate.Config{
Host: "WEAVIATE_INSTANCE_URL", // Replace with your Weaviate URL
Scheme: "https",
}
client, err := weaviate.NewClient(cfg)
if err != nil {
panic(err)
}
fields := []graphql.Field{
{Name: "question"},
{Name: "answer"},
{Name: "points"},
}
ctx := context.Background()
result, err := client.GraphQL().Get().
WithClassName("JeopardyQuestion").
WithFields(fields...).
Do(ctx)
if err != nil {
panic(err)
}
fmt.Printf("%v", result)
}
package io.weaviate;
import io.weaviate.client.Config;
import io.weaviate.client.WeaviateClient;
import io.weaviate.client.base.Result;
import io.weaviate.client.v1.graphql.model.GraphQLResponse;
import io.weaviate.client.v1.graphql.query.fields.Field;
public class App {
public static void main(String[] args) {
Config config = new Config("https", "WEAVIATE_INSTANCE_URL"); // Replace with your Weaviate URL
WeaviateClient client = new WeaviateClient(config);
Field title = Field.builder().name("question").build();
Field url = Field.builder().name("answer").build();
Field wordCount = Field.builder().name("points").build();
Result<GraphQLResponse> result = client.graphQL().get()
.withClassName("JeopardyQuestion")
.withFields(title, url, wordCount)
.run();
if (result.hasErrors()) {
System.out.println(result.getError());
return;
}
System.out.println(result.getResult());
}
}
echo '{
"query": "{
Get {
JeopardyQuestion {
question
answer
points
}
}
}"
}' | curl \
-X POST \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer learn-weaviate' \
-d @- \
https://edu-demo.weaviate.network/v1/graphql
{
Get {
JeopardyQuestion {
question
answer
points
}
}
}
Example response
The above query will result in something like the following:
{'points': 400.0, 'answer': 'Refrigerator Car', 'air_date': '1997-02-14', 'hasCategory': 'TRANSPORTATION', 'question': 'In the 19th century Gustavus Swift developed this type of railway car to preserve his packed meat', 'round': 'Jeopardy!'}
{'points': 800.0, 'hasCategory': 'FICTIONAL CHARACTERS', 'answer': 'Forsyte', 'air_date': '1998-05-27', 'question': 'Last name of Soames & Irene, the 2 principal characters in John Galsworthy\'s 3 novel "saga"', 'round': 'Double Jeopardy!'}
{'points': 500.0, 'answer': 'Duluth', 'air_date': '1996-12-17', 'hasCategory': 'MUSEUMS', 'question': 'This eastern Minnesota city is home to the Lake Superior Museum of Transportation', 'round': 'Jeopardy!'}
{'points': 1000.0, 'answer': 'Ear', 'air_date': '1988-11-16', 'hasCategory': 'HISTORY', 'round': 'Double Jeopardy!', 'question': "An eighteenth-century war was named for this part of Robert Jenkins' body, reputedly cut off by Spaniards"}
{'points': 400.0, 'answer': 'Bonnie Blair', 'air_date': '1997-02-28', 'hasCategory': 'SPORTS', 'round': 'Jeopardy!', 'question': "At the 1994 Olympics, this U.S. woman speed skater surpassed Eric Heiden's medal total"}
{'points': 1600.0, 'answer': 'Turkish', 'air_date': '2008-03-24', 'hasCategory': 'LANGUAGES', 'question': 'In the 1920s this language of Anatolia switched from the Arabic to the Latin alphabet', 'round': 'Double Jeopardy!'}
{'points': 100.0, 'answer': 'Ireland', 'air_date': '1998-10-01', 'hasCategory': 'POTPOURRI', 'round': 'Jeopardy!', 'question': "Country in which you'd find the Book of Kells"}
{'points': 800.0, 'answer': 'Ichabod Crane', 'air_date': '2008-01-03', 'hasCategory': 'LITERATURE', 'round': 'Double Jeopardy!', 'question': 'Washington Irving based this character on his friend Jesse Merwin, a schoolteacher'}
{'points': 300.0, 'air_date': '1997-12-05', 'hasCategory': 'LITERATURE', 'answer': '"The Prince and the Pauper"', 'question': 'Tom Canty, born in a slum called Offal Court, & Edward Tudor are the title characters in this Twain novel', 'round': 'Jeopardy!'}
{'points': 500.0, 'answer': 'Seattle', 'air_date': '1999-05-10', 'hasCategory': 'U.S. CITIES', 'round': 'Jeopardy!', 'question': "The site of the World's Fair in 1962, it's flanked on the west by Puget Sound & on the east by Lake Washington"}
Order of retrieved objects
Without any arguments, the objects are retrieved according to their ID.
Accordingly, such a Get
query is not suitable for a substantive object retrieval strategy. Consider the Cursor API for that purpose.
Get
groupBy
You can use retrieve groups of objects that match the query.
The groups are defined by a property, and the number of groups and objects per group can be limited.
groupBy
limitationsgroupBy
only works withnear<Media>
operators.- The
groupBy
path
is limited to one property or cross-reference. Nested paths are not supported.
Syntax
{
Get{
<Class>(
<vectorSearchOperator> # e.g. nearVector, nearObject, nearText
groupBy:{
path: [<propertyName>] # Property to group by (only one property or cross-reference)
groups: <number> # Max. number of groups
objectsPerGroup: <number> # Max. number of objects per group
}
) {
_additional {
group {
id # An identifier for the group in this search
groupedBy{ value path } # Value and path of the property grouped by
count # Count of objects in this group
maxDistance # Maximum distance from the group to the query vector
minDistance # Minimum distance from the group to the query vector
hits { # Where the actual properties for each grouped objects will be
<properties> # Properties of the individual object
_additional {
id # UUID of the individual object
vector # The vector of the individual object
distance # The distance from the individual object to the query vector
}
}
}
}
}
}
}
Example usage:
- Python Client v4
- Raw GraphQL
questions = client.collections.get("JeopardyQuestion")
response = questions.query.near_text(
query="animals",
distance=0.2,
group_by=wvc.query.GroupBy(
prop="points",
number_of_groups=3,
objects_per_group=5
)
)
for k, v in response.groups.items(): # View by group
print(k, v)
for o in response.objects: # View by object
print(o)
The other clients do not yet natively support groupby operations. Please use "raw" graphql queries to perform groupby operations.
{
Get{
JeopardyQuestion(
nearText: {
concepts: ["animals"],
distance: 0.2
}
groupBy: { # How to group the results
path: ["points"]
groups: 3
objectsPerGroup: 5
}
) {
_additional {
group { # Data to be returned
id
groupedBy{ value path }
count
hits { # Actual properties to be retrieved
question
answer
_additional {
id
distance
}
}
}
}
}
}
}
Consistency levels
v1.19
Where replication is enabled, you can specify a consistency
argument with a Get
query. The available options are:
ONE
QUORUM
(Default)ALL
Read more about consistency levels here.
- Python Client v4
- Python Client v3
- JS/TS Client v2
- Go
- Java
- GraphQL
import weaviate
import weaviate.classes as wvc
import os
client = weaviate.connect_to_local()
try:
questions = client.collections.get("JeopardyQuestion").with_consistency_level(consistency_level=wvc.config.ConsistencyLevel.QUORUM)
response = collection.query.fetch_objects()
for o in response.objects:
print(o.properties) # Inspect returned objects
finally:
client.close()
import weaviate
from weaviate.data.replication import ConsistencyLevel
client = weaviate.Client("http://localhost:8080")
resp = (
client.query.get("Article", ["name"])
.with_additional("isConsistent")
.with_consistency_level(ConsistencyLevel.QUORUM)
.do()
)
print(f"resp: {resp}")
import weaviate from 'weaviate-ts-client';
const client = weaviate.client({
scheme: 'http',
host: 'localhost:8080',
});
const response = await client.graphql
.get()
.withClassName('Article')
.withFields('_additional { id isConsistent }')
.withConsistencyLevel('QUORUM')
.do();
console.log(JSON.stringify(response, null, 2));
resp, err := client.GraphQL().Get().
WithClassName("Article").
WithFields(fields...).
WithConsistencyLevel(replication.ConsistencyLevel.QUORUM).
Do(ctx)
Field name = Field.builder().name("name").build();
Field _additional = Field.builder()
.name("_additional")
.fields(new Field[]{Field.builder().name("isConsistent").build()})
.build();
Result<GraphQLResponse> result = client.graphQL().get()
.withClassName("Article").withConsistencyLevel(ConsistencyLevel.QUORUM)
.withFields(name, _additional)
.run();
{
Get {
Article (consistencyLevel: QUORUM) {
name
_additional {
isConsistent
}
}
}
}
Multi-tenancy
v1.20
In a multi-tenancy collection, each Get
query must specify a tenant.
- Python Client v4
- Python Client v3
- JS/TS Client v2
- Java
- Go
- GraphQL
multi_collection = client.collections.get("MultiTenancyCollection")
# Get collection specific to the required tenant
multi_tenantA = multi_collection.with_tenant("tenantA")
# Query tenantA
result = multi_tenantA.query.fetch_objects(
limit=2,
)
print(result.objects[0].properties)
result = (
client.query.get("MultiTenancyCollection", ["question"])
.with_tenant("tenantA")
.do()
)
const multiCollection = client.collections.get('MultiTenancyCollection');
const multiTenantA = multiCollection.withTenant('tenantA')
const objectA = await multiTenantA.query.fetchObjects({
limit: 2
})
console.log(objectA.objects)
Result<GraphQLResponse> result = client.graphQL().get()
.withClassName("MultiTenancyCollection")
.withFields(Field.builder().name("question").build())
.withTenant("tenantA")
.run();
result, err := client.GraphQL().Get().
WithClassName("MultiTenancyCollection").
WithFields(graphql.Field{Name: "question"}).
WithTenant("tenantA").
Do(ctx)
{
Get {
MultiTenancyCollection (
tenant: "tenantA"
limit: 2
) {
name
}
}
}
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-native 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.
Weaviate supports cross-references between objects. Each cross-reference behaves like a property.
You can retrieve cross-referenced properties with a Get
query.
- Python Client v4
- Python Client v3
- JS/TS Client v2
- Go
- Java
- Curl
- GraphQL
questions = client.collections.get("JeopardyQuestion")
response = questions.query.fetch_objects(
return_references=wvc.query.QueryReference(
link_on="hasCategory",
return_properties=["title"]
)
)
for o in response.objects:
print(f"References for {o.uuid}")
for ro in o.references["hasCategory"].objects: # Inspect returned references
print(ro.properties)
import weaviate
client = weaviate.Client(
"https://WEAVIATE_INSTANCE_URL", # Replace with your Weaviate URL
)
result = client.query.get("JeopardyQuestion", ["question", "answer", "points", "hasCategory {... on JeopardyCategory {title }}"]).do()
print(result)
import weaviate from 'weaviate-ts-client';
const client = weaviate.client({
scheme: 'http',
host: 'localhost:8080',
});
const response = await client.graphql
.get()
.withClassName('Article')
.withFields('title url wordCount inPublication {... on Publication {name}}')
.do();
console.log(response);
package main
import (
"context"
"fmt"
"github.com/weaviate/weaviate-go-client/v5/weaviate"
"github.com/weaviate/weaviate-go-client/v5/weaviate/graphql"
)
func main() {
cfg := weaviate.Config{
Host: "localhost:8080",
Scheme: "http",
}
client, err := weaviate.NewClient(cfg)
if err != nil {
panic(err)
}
ctx := context.Background()
fields := []graphql.Field{
{Name: "title"},
{Name: "url"},
{Name: "wordCount"},
{Name: "inPublication", Fields: []graphql.Field{
{Name: "... on Publication", Fields: []graphql.Field{
{Name: "name"},
}},
}},
}
result, err := client.GraphQL().Get().
WithClassName("Article").
WithFields(fields...).
Do(ctx)
if err != nil {
panic(err)
}
fmt.Printf("%v", result)
}
package io.weaviate;
import io.weaviate.client.Config;
import io.weaviate.client.WeaviateClient;
import io.weaviate.client.base.Result;
import io.weaviate.client.v1.graphql.model.GraphQLResponse;
import io.weaviate.client.v1.graphql.query.fields.Field;
public class App {
public static void main(String[] args) {
Config config = new Config("http", "localhost:8080");
WeaviateClient client = new WeaviateClient(config);
Field title = Field.builder().name("title").build();
Field url = Field.builder().name("url").build();
Field wordCount = Field.builder().name("wordCount").build();
Field inPublication = Field.builder()
.name("inPublication")
.fields(new Field[]{
Field.builder()
.name("... on Publication")
.fields(new Field[]{
Field.builder().name("name").build()
})
.build()
})
.build();
Result<GraphQLResponse> result = client.graphQL().get()
.withClassName("Article")
.withFields(title, url, wordCount, inPublication)
.run();
if (result.hasErrors()) {
System.out.println(result.getError());
return;
}
System.out.println(result.getResult());
}
}
echo '{
"query": "{
Get {
Article {
title
url
wordCount
inPublication {
... on Publication {
name
}
}
}
}
}"
}' | curl \
-X POST \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer learn-weaviate' \
-d @- \
https://edu-demo.weaviate.network/v1/graphql
{
Get {
JeopardyQuestion {
question
answer
points
hasCategory { # the reference property
... on JeopardyCategory { # the destination class
title # the property related to target class
}
}
}
}
}
Expected response
{
"data": {
"Get": {
"JeopardyQuestion": [
{
"answer": "Jonah",
"hasCategory": [
{
"title": "THE BIBLE"
}
],
"points": 100,
"question": "This prophet passed the time he spent inside a fish offering up prayers"
},
// shortened for brevity
]
}
}
}
Additional properties / metadata
Various metadata properties may be retrieved with Get{}
requests. They include:
Property | Description |
---|---|
id | Object id |
vector | Object vector |
generate | Generative module outputs |
rerank | Reranker module outputs |
creationTimeUnix | Object creation time |
lastUpdateTimeUnix | Object last updated time |
distance | Vector distance to query (vector search only) |
certainty | Vector distance to query, normalized to certainty (vector search only) |
score | Search score (BM25 and hybrid only) |
explainScore | Explanation of the score (BM25 and hybrid only) |
classification | Classification outputs |
featureProjection | Feature projection outputs |
They are returned through the _additional
properties in the response.
For further information see:
Search operators
The following search operators are available.
Argument | Description | Required integration type | Learn more |
---|---|---|---|
nearObject | Vector search using a Weaviate object | none | Learn more |
nearVector | Vector search using a raw vector | none | Learn more |
nearText | Vector search using a text query | Text embedding model | |
nearImage | Vector search using an image | Multi-modal embedding model | |
hybrid | Combine vector and BM25 search results | none | Learn more |
bm25 | Keyword search with BM25F ranking | none | Learn more |
For further information see:
Conditional filters
Get{}
queries can be combined with a conditional filter.
For further information see:
Additional operators
Get{}
queries can be combined with additional operators such as limit
, offset
, autocut
, after
or sort
.
For further information see:
Related pages
Questions and feedback
If you have any questions or feedback, let us know in the user forum.