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
- 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={
"X-OpenAI-Api-Key": "YOUR-OPENAI-API-KEY", # Only needed for `nearText` or `hybrid` queries
},
)
import weaviate, { WeaviateClient, ApiKey } from 'weaviate-ts-client';
// Instantiate the client with the auth config
const client: WeaviateClient = weaviate.client({
scheme: 'https',
host: 'edu-demo.weaviate.network',
apiKey: new ApiKey('learn-weaviate'),
headers: {
'X-OpenAI-Api-Key': 'YOUR-OPENAI-API-KEY', // Only needed for `nearText` or `hybrid` queries
},
});
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{
"X-OpenAI-Api-Key": "YOUR-OPENAI-API-KEY", // Only needed for `nearText` or `hybrid` queries
},
)
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>() { {
put("X-OpenAI-Api-Key", "YOUR-OPENAI-API-KEY"); // Only needed for `nearText` or `hybrid` queries
} };
Config config = new Config("https", "edu-demo.weaviate.network", headers);
WeaviateClient client = WeaviateAuthClient.apiKey(config, "learn-weaviate");
Note: OpenAI API key only needed for nearText
or hybrid
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
Get{} syntax and query structureโ
The Get{}
function fetches fields described in the schema. For example, if you've created a schema with a class JeopardyQuestion
which has the properties question
, answer
and points
, you can query it as follows:
- Python
- JavaScript
- 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)
const weaviate = require('weaviate-ts-client');
const client = weaviate.client({
scheme: 'https',
host: 'some-endpoint.weaviate.network', // Replace with your Weaviate URL
});
client.graphql
.get()
.withClassName('JeopardyQuestion')
.withFields('question answer points')
.do()
.then(res => {
console.log(res)
})
.catch(err => {
console.error(err)
});
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' \
-d @- \
https://some-endpoint.weaviate.network/v1/graphql
{
Get {
JeopardyQuestion {
question
answer
points
}
}
}
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
]
}
}
}
The order of object retrieval is not guaranteed in a Get
query without any search parameters or filters. Accordingly, such a Get
query is not suitable for any substantive object retrieval strategy. Consider the Cursor API for that purpose.
groupBy argumentโ
You can use a groupBy argument to retrieve groups of objects from Weaviate. This functionality offers the advantage of maintaining granular search results by searching through detailed or segmented objects (e.g. chunks of documents), while also enabling you to step back and view the broader context of the objects (e.g. documents as a whole).
The groupBy{}
argument is structured as follows for the Get{}
function:
As of 1.19
, the groupBy
path
is limited to one property or cross-reference. Nested paths are current not supported.
{
Get{
<Class>(
<vectorSearchParameter> # 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
}
}
}
}
}
}
}
Take a collection of Passage
objects for example, each object belonging to a Document
. If searching through Passage
objects, you can group the results according to any property of the Passage
, including the cross-reference property that represents the Document
each Passage
is associated with.
The groups
and objectsPerGroup
limits are customizable. So in this example, you could retrieve the top 1000 objects and group them to identify the 3 most relevant Document
objects, based on the top 3 Passage
objects from each Document
.
More concretely, a query such as below:
Example Get query with groupBy
{
Get{
Passage(
limit: 100
nearObject: {
id: "00000000-0000-0000-0000-000000000001"
}
groupBy: {
path: ["content"]
groups: 2
objectsPerGroup: 2
}
){
_additional {
id
group {
id
count
groupedBy { value path }
maxDistance
minDistance
hits{
content
ofDocument {
... on Document {
_additional {
id
}
}
}
_additional {
id
distance
}
}
}
}
}
}
}
Will result in the following response:
Corresponding response
{
"data": {
"Get": {
"Passage": [
{
"_additional": {
"group": {
"count": 1,
"groupedBy": {
"path": [
"content"
],
"value": "Content of passage 1"
},
"hits": [
{
"_additional": {
"distance": 0,
"id": "00000000-0000-0000-0000-000000000001"
},
"content": "Content of passage 1",
"ofDocument": [
{
"_additional": {
"id": "00000000-0000-0000-0000-000000000011"
}
}
]
}
],
"id": 0,
"maxDistance": 0,
"minDistance": 0
},
"id": "00000000-0000-0000-0000-000000000001"
}
},
{
"_additional": {
"group": {
"count": 1,
"groupedBy": {
"path": [
"content"
],
"value": "Content of passage 2"
},
"hits": [
{
"_additional": {
"distance": 0.00078231096,
"id": "00000000-0000-0000-0000-000000000002"
},
"content": "Content of passage 2",
"ofDocument": [
{
"_additional": {
"id": "00000000-0000-0000-0000-000000000011"
}
}
]
}
],
"id": 1,
"maxDistance": 0.00078231096,
"minDistance": 0.00078231096
},
"id": "00000000-0000-0000-0000-000000000002"
}
}
]
}
}
}
Consistency levelsโ
v1.19
onwardsWhere 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.
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}")
const weaviate = require('weaviate-ts-client');
const client = weaviate.client({
scheme: 'http',
host: 'localhost:8080',
});
const resp = await client.graphql
.get()
.withClassName('Article')
.withFields('_additional { id isConsistent }')
.withConsistencyLevel('ONE')
.do();
console.log(`resp: ${JSON.stringify(resp)}`);
import weaviate, { WeaviateClient } from 'weaviate-ts-client';
const client: WeaviateClient = weaviate.client({
scheme: 'http',
host: 'localhost:8080',
});
const resp = await client.graphql
.get()
.withClassName('Article')
.withFields('_additional { id isConsistent }')
.withConsistencyLevel('ONE')
.do();
console.log(`resp: ${JSON.stringify(resp)}`);
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
}
}
}
}
Query beacon referencesโ
If you've set a beacon reference (cross-reference) in the schema, you can query it as follows:
- Python
- JavaScript
- 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)
const weaviate = require('weaviate-client');
const client = weaviate.client({
scheme: 'http',
host: 'localhost:8080',
});
client.graphql
.get()
.withClassName('Article')
.withFields('title url wordCount inPublication {... on Publication {name}}')
.do()
.then(res => {
console.log(res)
})
.catch(err => {
console.error(err)
});
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' \
-d @- \
http://localhost:8080/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โ
For every Get{} request you can get additional information about the returned data object(s) by using additional properties. You can recognize these properties because they are in the object _additional{}
. Additional properties can help you interpret query results and can for example be used for projection and visualization of the retrieved data. An overview of all additional properties and how to use them is documented here.
Vector Search Operatorsโ
To combine Get { }
with a vector search argument, here is an overview of the supported arguments and links to their detailed documentation:
Argument | Description | Required modules (at least one of) | Learn more |
---|---|---|---|
nearObject | Find the nearest neighbors of an object referenced by its id | none - works out of the box | Learn more |
nearVector | Find the nearest neighbors to any vector | none - works out of the box | Learn more |
nearText | Vectorize a text query and perform a vector search based on it | text2vec-transformers , text2vec-contextionary , text2vec-openai , multi2vec-clip , text2vec-huggingface , text2vec-cohere | Transformers, Contextionary, OpenAI, CLIP, Hugging Face, Cohere |
nearImage | Vectorize an image and perform a vector search based on it | multi2vec-clip , img2vec-neural | CLIP, Img2Vec |
hybrid | Combine dense and sparse vectors to deliver best of both search methods | none - works out of the box | Learn more |
bm25 | Keyword search with BM25F ranking | none - works out of the box | Learn more |
Filtersโ
Get{}
functions can be extended with search filters (both semantic filters and traditional filters). Because the filters work on multiple core functions (like Aggregate{}
) there is a specific documentation page dedicated to filters.
Sortingโ
Note: Support for sorting was added in v1.13.0
.
You can sort results by any primitive property, typically a text
, string
,
number
, or int
property. When a query has a natural order (e.g. because of a
near<Media>
vector search), adding a sort operator will override the order.
See filters โ sorting for more information.
More Resourcesโ
If you can't find the answer to your question here, please look at the:
- Frequently Asked Questions. Or,
- Knowledge base of old issues. Or,
- For questions: Stackoverflow. Or,
- For more involved discussion: Weaviate Community Forum. Or,
- We also have a Slack channel.