GraphQL - Get{}
You can try these queries on our demo instance (https://edu-demo.weaviate.network). You can authenticate against it with the read-only Weaviate API key learn-weaviate
, and run the query with your preferred Weaviate client.
We include client instantiation examples below:
edu-demo
client instantiation
- Python
- JavaScript/TypeScript
- Go
- Java
- Curl
import weaviate
# Instantiate the client with the auth config
client = weaviate.Client(
url='https://edu-demo.weaviate.network',
auth_client_secret=weaviate.AuthApiKey(api_key='learn-weaviate'),
additional_headers={
# Only needed if using an inference service (e.g. `nearText`, `hybrid` or `generative` queries)
'X-OpenAI-Api-Key': 'YOUR-OPENAI-API-KEY',
},
)
import weaviate, { ApiKey } from 'weaviate-ts-client';
// Instantiate the client with the auth config
const client = weaviate.client({
scheme: 'https',
host: 'edu-demo.weaviate.network',
apiKey: new ApiKey('learn-weaviate'),
headers: {
// Only needed if using an inference service (e.g. `nearText`, `hybrid` or `generative` queries)
'X-OpenAI-Api-Key': process.env['OPENAI_API_KEY'], // Replace with your API key
},
});
package main
import (
"context"
"fmt"
"github.com/weaviate/weaviate-go-client/v4/weaviate"
)
// Instantiate the client with the auth config
cfg := weaviate.Config{
Host:"edu-demo.weaviate.network",
Scheme: "https",
AuthConfig: auth.ApiKey{Value: "learn-weaviate"},
Headers: map[string]string{
// Only needed if using an inference service (e.g. `nearText`, `hybrid` or `generative` queries)
"X-OpenAI-Api-Key": "YOUR-OPENAI-API-KEY",
},
}
client, err := weaviate.NewClient(cfg)
if err != nil{
fmt.Println(err)
}
import io.weaviate.client.Config;
import io.weaviate.client.WeaviateAuthClient;
Map<String, String> headers = new HashMap<String, String>() { {
// Only needed if using an inference service (e.g. `nearText`, `hybrid` or `generative` queries)
put("X-OpenAI-Api-Key", "YOUR-OPENAI-API-KEY");
} };
Config config = new Config("https", "edu-demo.weaviate.network", headers);
WeaviateClient client = WeaviateAuthClient.apiKey(config, "learn-weaviate");
Note: Inference (e.g. OpenAI) API key only needed if using an inference service (e.g. nearText
, hybrid
or generative
queries)
curl https://edu-demo.weaviate.network/v1/meta \
-H 'Content-Type: application/json' \
-H "X-OpenAI-Api-Key: YOUR-OPENAI-API-KEY" \
-H "Authorization: Bearer YOUR-WEAVIATE-API-KEY" | jq
Overview
The Get{}
function is for retrieving individual objects.
Syntax and query structure
The Get{}
function requires the target class name, and the properties to be fetched.
For example, the following will fetch JeopardyQuestion
objects and their question
, answer
and points
properties:
- Python
- JavaScript/TypeScript
- Go
- Java
- Curl
- GraphQL
import weaviate
client = weaviate.Client(
"https://some-endpoint.weaviate.network", # 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: 'some-endpoint.weaviate.network', // 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/v4/weaviate"
"github.com/weaviate/weaviate-go-client/v4/weaviate/graphql"
)
func main() {
cfg := weaviate.Config{
Host: "some-endpoint.weaviate.network", // 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", "some-endpoint.weaviate.network"); // 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:
{
"data": {
"Get": {
"JeopardyQuestion": [
{
"answer": "Jonah",
"points": 100,
"question": "This prophet passed the time he spent inside a fish offering up prayers"
},
// shortened for brevity
]
}
}
}
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.
groupBy argument
You can use groupBy
to retrieve groups of objects from Weaviate. The groupBy{}
argument is structured as follows for the Get{}
function:
groupBy
can only be used withnear<Media>
operators. It is not possible to use it withbm25
orhybrid
queries.- The
groupBy
path
is limited to one property or cross-reference. Nested paths are current not supported.
{
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
}
}
}
}
}
}
}
Consistency levels
v1.19
Where replication is configured, the Get{}
function can be configured to return results with different levels of consistency. This is useful when you want to retrieve the most up-to-date data, or when you want to retrieve data as fast as possible.
The available consistency options are:
ONE
QUORUM
ALL
Read more about consistency levels here.
- Python
- JavaScript/TypeScript
- Go
- Java
- GraphQL
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.ONE)
.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('ONE')
.do();
console.log(JSON.stringify(response, null, 2));
resp, err := client.GraphQL().Get().
WithClassName("Article").
WithFields(fields...).
WithConsistencyLevel(replication.ConsistencyLevel.ONE).
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.ONE)
.withFields(name, _additional)
.run();
{
Get {
Article (consistencyLevel: ONE) {
name
_additional {
isConsistent
}
}
}
}
Multi-tenancy
v1.20
Where multi-tenancy is configured, the Get{}
function can be configured to return results from a specific tenant.
You can do so by specifying the tenant
parameter in the GraphQL query as shown below, or using the equivalent client function.
{
Get {
Article (
tenant: "tenantA"
limit: 1
) {
name
}
}
}
Cross-references
You can retrieve any cross-referenced properties.
- Python
- JavaScript/TypeScript
- Go
- Java
- Curl
- GraphQL
import weaviate
client = weaviate.Client(
"https://some-endpoint.weaviate.network", # 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/v4/weaviate"
"github.com/weaviate/weaviate-go-client/v4/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 modules (at least one of) | 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 | text2vec-xxx | Transformers, Contextionary, OpenAI, CLIP, Hugging Face, Cohere |
nearImage | Vector search using an image | multi2vec-clip , img2vec-neural | CLIP, Img2Vec |
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: