weaviate.gql

GraphQL module used to create get and/or aggregate GraphQL requests from Weaviate.

class weaviate.gql.Query(connection: weaviate.connect.connection.Connection)

Bases: object

Query class used to make get and/or aggregate GraphQL queries.

Initialize a Classification class instance.

Parameters

connection (weaviate.connect.Connection) – Connection object to an active and running Weaviate instance.

aggregate(class_name: str)weaviate.gql.aggregate.AggregateBuilder

Instantiate an AggregateBuilder for GraphQL aggregate requests.

Parameters

class_name (str) – Class name of the objects to be aggregated.

Returns

An AggregateBuilder to make GraphQL aggregate requests from weaviate.

Return type

AggregateBuilder

get(class_name: str, properties: Union[List[str], str])weaviate.gql.get.GetBuilder

Instantiate a GetBuilder for GraphQL get requests.

Parameters
  • class_name (str) – Class name of the objects to interact with.

  • properties (list of str or str) – Properties of the objects to get.

Returns

A GetBuilder to make GraphQL get requests from weaviate.

Return type

GetBuilder

raw(gql_query: str)dict

Allows to send simple graph QL string queries. Be cautious of injection risks when generating query strings.

Parameters

gql_query (str) – GraphQL query as a string.

Returns

Data response of the query.

Return type

dict

Examples

>>> query = """
... {
...     Get {
...         Article(limit: 2) {
...         title
...         hasAuthors {
...             ... on Author {
...                 name
...                 }
...             }
...         }
...     }
... }
... """
>>> client.query.raw(query)
{
"data": {
    "Get": {
    "Article": [
        {
        "hasAuthors": [
            {
            "name": "Jonathan Wilson"
            }
        ],
        "title": "Sergio Agüero has been far more than a great goalscorer for
                    Manchester City"
        },
        {
        "hasAuthors": [
            {
            "name": "Emma Elwick-Bates"
            }
        ],
        "title": "At Swarovski, Giovanna Engelbert Is Crafting Jewels As Exuberantly
                    Joyful As She Is"
        }
    ]
    }
},
"errors": null
}
Raises
  • TypeError – If ‘gql_query’ is not of type str.

  • requests.ConnectionError – If the network connection to weaviate fails.

  • weaviate.UnexpectedStatusCodeException – If weaviate reports a none OK status.

weaviate.gql.aggregate

GraphQL Aggregate command.

class weaviate.gql.aggregate.AggregateBuilder(class_name: str, connection: weaviate.connect.connection.Connection)

Bases: weaviate.gql.filter.GraphQL

AggregateBuilder class used to aggregate Weaviate objects.

Initialize a AggregateBuilder class instance.

Parameters
  • class_name (str) – Class name of the objects to be aggregated.

  • connection (weaviate.connect.Connection) – Connection object to an active and running Weaviate instance.

build()str

Build the query and return the string.

Returns

The GraphQL query as a string.

Return type

str

with_fields(field: str)weaviate.gql.aggregate.AggregateBuilder

Include a field in the aggregate query.

Parameters

field (str) – Field to include in the aggregate query. e.g. ‘<property_name> { count }’

Returns

Updated AggregateBuilder.

Return type

weaviate.gql.aggregate.AggregateBuilder

with_group_by_filter(properties: List[str])weaviate.gql.aggregate.AggregateBuilder

Add a group by filter to the query. Might requires the user to set an additional group by clause using with_fields(..).

Parameters

properties (list of str) – list of properties that are included in the group by filter. Generates a filter like: ‘groupBy: [“property1”, “property2”]’ from a list [“property1”, “property2”]

Returns

Updated AggregateBuilder.

Return type

weaviate.gql.aggregate.AggregateBuilder

with_meta_count()weaviate.gql.aggregate.AggregateBuilder

Set Meta Count to True.

Returns

Updated AggregateBuilder.

Return type

weaviate.gql.aggregate.AggregateBuilder

with_where(content: dict)weaviate.gql.aggregate.AggregateBuilder

Set ‘where’ filter.

Parameters

content (dict) – The where filter to include in the aggregate query. See examples below.

Examples

The content prototype is like this:

>>> content = {
...     'operator': '<operator>',
...     'operands': [
...         {
...             'path': [path],
...             'operator': '<operator>'
...             '<valueType>': <value>
...         },
...         {
...             'path': [<matchPath>],
...             'operator': '<operator>',
...             '<valueType>': <value>
...         }
...     ]
... }

This is a complete where filter but it does not have to be like this all the time.

Single operand:

>>> content = {
...     'path': ["wordCount"],    # Path to the property that should be used
...     'operator': 'GreaterThan',  # operator
...     'valueInt': 1000       # value (which is always = to the type of the path property)
... }

Or

>>> content = {
...     'path': ["id"],
...     'operator': 'Equal',
...     'valueString': "e5dc4a4c-ef0f-3aed-89a3-a73435c6bbcf"
... }

Multiple operands:

>>> content = {
...     'operator': 'And',
...     'operands': [
...         {
...             'path': ["wordCount"],
...             'operator': 'GreaterThan',
...             'valueInt': 1000
...         },
...         {
...             'path': ["wordCount"],
...             'operator': 'LessThan',
...             'valueInt': 1500
...         }
...     ]
... }
Returns

Updated AggregateBuilder.

Return type

weaviate.gql.aggregate.AggregateBuilder

weaviate.gql.filter

GraphQL filters for Get and Aggregate commands. GraphQL abstract class for GraphQL commands to inherit from.

class weaviate.gql.filter.Ask(content: dict)

Bases: weaviate.gql.filter.Filter

Ask class used to filter weaviate objects by asking a question.

Initialize a Ask class instance.

Parameters

content (list) – The content of the ask clause.

Raises
  • TypeError – If ‘content’ is not of type dict.

  • ValueError – If ‘content’ has key “certainty” but the value is not float.

  • TypeError – If ‘content’ has key “properties” but the type is not list or str.

class weaviate.gql.filter.Filter(content: dict)

Bases: abc.ABC

A base abstract class for all filters.

Initialize a Filter class instance.

Parameters

content (dict) – The content of the Filter clause.

class weaviate.gql.filter.GraphQL(connection: weaviate.connect.connection.Connection)

Bases: abc.ABC

A base abstract class for GraphQL commands, such as Get, Aggregate.

Initialize a GraphQL abstract class instance.

Parameters

connection (weaviate.connect.Connection) – Connection object to an active and running weaviate instance.

abstract build()str

Build method to be overloaded by the child classes. It should return the GraphQL query as a str.

Returns

The query.

Return type

str

do()dict

Builds and runs the query.

Returns

The response of the query.

Return type

dict

Raises
class weaviate.gql.filter.NearImage(content: dict)

Bases: weaviate.gql.filter.Filter

NearObject class used to filter weaviate objects.

Initialize a NearImage class instance.

Parameters

content (list) – The content of the nearImage clause.

Raises
  • TypeError – If ‘content’ is not of type dict.

  • TypeError – If ‘content[“image”]’ is not of type str.

  • ValueError – If ‘content’ has key “certainty” but the value is not float.

class weaviate.gql.filter.NearObject(content: dict)

Bases: weaviate.gql.filter.Filter

NearObject class used to filter weaviate objects.

Initialize a NearVector class instance.

Parameters

content (list) – The content of the nearVector clause.

Raises
  • TypeError – If ‘content’ is not of type dict.

  • ValueError – If ‘content’ has key “certainty” but the value is not float.

  • TypeError – If ‘id’/’beacon’ key does not have a value of type str!

class weaviate.gql.filter.NearText(content: dict)

Bases: weaviate.gql.filter.Filter

NearText class used to filter weaviate objects. Can be used with text models only (text2vec). E.g.: text2vec-contextionary, text2vec-transformers.

Initialize a NearText class instance.

Parameters

content (dict) – The content of the nearText clause.

Raises
  • TypeError – If ‘content’ is not of type dict.

  • ValueError – If ‘content’ has key “certainty” but the value is not float.

class weaviate.gql.filter.NearVector(content: dict)

Bases: weaviate.gql.filter.Filter

NearVector class used to filter weaviate objects.

Initialize a NearVector class instance.

Parameters

content (list) – The content of the nearVector clause.

Raises
  • TypeError – If ‘content’ is not of type dict.

  • ValueError – If ‘content’ does not contain “vector”.

  • TypeError – If ‘content[“vector”]’ is not of type list.

  • AttributeError – If invalid ‘content’ keys are provided.

  • ValueError – If ‘content’ has key “certainty” but the value is not float.

class weaviate.gql.filter.Where(content: dict)

Bases: weaviate.gql.filter.Filter

Where filter class used to filter weaviate objects.

Initialize a Where filter class instance.

Parameters

content (dict) – The content of the where filter clause.

Raises
  • TypeError – If ‘content’ is not of type dict.

  • ValueError – If a mandatory key is missing in the filter content.

weaviate.gql.get

GraphQL Get command.

class weaviate.gql.get.GetBuilder(class_name: str, properties: Union[List[str], str], connection: weaviate.connect.connection.Connection)

Bases: weaviate.gql.filter.GraphQL

GetBuilder class used to create GraphQL queries.

Initialize a GetBuilder class instance.

Parameters
  • class_name (str) – Class name of the objects to interact with.

  • properties (list of str or str) – Properties of the objects to interact with.

  • connection (weaviate.connect.Connection) – Connection object to an active and running Weaviate instance.

Raises

TypeError – If argument/s is/are of wrong type.

build()str

Build query filter as a string.

Returns

The GraphQL query as a string.

Return type

str

with_ask(content: dict)weaviate.gql.get.GetBuilder

Ask a question for which weaviate will retreive the answer from your data. This filter can be used only with QnA module: qna-transformers.

Parameters

content (dict) – The content of the ask filter to set. See examples below.

Examples

Content full prototype:

>>> content = {
...     'question' : <str>,
...     'certainty': <float>, # Optional
...     'properties': <list of str or str>
... }

Full content:

>>> content = {
...     'question' : "What is the NLP?",
...     'certainty': 0.7,
...     'properties': ['body'] # search the answer in these properties only.
... }

Minimal content:

>>> content = {
...     'question' : "What is the NLP?"
... }
Returns

Updated GetBuilder.

Return type

weaviate.gql.get.GetBuilder

with_limit(limit: int)weaviate.gql.get.GetBuilder

The limit of objects returned.

Parameters

limit (dict) – The max number of objects returned.

Returns

Updated GetBuilder.

Return type

weaviate.gql.get.GetBuilder

Raises

ValueError – If ‘limit’ is non-positive.

with_near_image(content: dict, encode: bool = True)weaviate.gql.get.GetBuilder

Set nearImage filter.

Parameters
  • content (dict) – The content of the nearObject filter to set. See examples below.

  • encode (bool, optional) – Whether to encode the content[“image”] to base64 and convert to string. If True, the content[“image”] can be an image path or a file opened in binary read mode. If False, the content[“image”] MUST be a base64 encoded string (NOT bytes, i.e. NOT binary string that looks like this: b’BASE64ENCODED’ but simple ‘BASE64ENCODED’). By default True.

Examples

Content prototype:

>>> {
...     'image': "e5dc4a4c-ef0f-3aed-89a3-a73435c6bbcf",
...     'certainty': 0.7 # Optional
... }

With encoded True:

>>> content = {
...     'image': "my_image_path.png",
...     'certainty': 0.7 # Optional
... }
>>> query = client.query.get('Image', 'description')        ...     .with_near_image(content, encode=True) # <- encode MUST be set to True

OR

>>> my_image_file = open("my_image_path.png", "br")
>>> content = {
...     'image': my_image_file,
...     'certainty': 0.7 # Optional
... }
>>> query = client.query.get('Image', 'description')        ...     .with_near_image(content, encode=True) # <- encode MUST be set to True
>>> my_image_file.close()

With encoded False:

>>> from weaviate.util import image_encoder_b64, image_decoder_b64
>>> encoded_image = image_encoder_b64("my_image_path.png")
>>> content = {
...     'image': encoded_image,
...     'certainty': 0.7 # Optional
... }
>>> query = client.query.get('Image', 'description')        ...     .with_near_image(content, encode=False) # <- encode MUST be set to False

OR

>>> from weaviate.util import image_encoder_b64, image_decoder_b64
>>> with open("my_image_path.png", "br") as my_image_file:
...     encoded_image = image_encoder_b64(my_image_file)
>>> content = {
...     'image': encoded_image,
...     'certainty': 0.7 # Optional
... }
>>> query = client.query.get('Image', 'description')        ...     .with_near_image(content, encode=False) # <- encode MUST be set to False

Encode Image yourself:

>>> import base64
>>> with open("my_image_path.png", "br") as my_image_file:
...     encoded_image = base64.b64encode(my_image_file.read()).decode("utf-8")
>>> content = {
...     'image': encoded_image,
...     'certainty': 0.7 # Optional
... }
>>> query = client.query.get('Image', 'description')        ...     .with_near_image(content, encode=False) # <- encode MUST be set to False
Returns

Updated GetBuilder.

Return type

weaviate.gql.get.GetBuilder

Raises

AttributeError – If another ‘near’ filter was already set.

with_near_object(content: dict)weaviate.gql.get.GetBuilder

Set nearObject filter.

Parameters

content (dict) – The content of the nearObject filter to set. See examples below.

Examples

Content prototype:

>>> {
...     'id': "e5dc4a4c-ef0f-3aed-89a3-a73435c6bbcf",
...     'certainty': 0.7 # Optional
... }
>>> # alternatively
>>> {
...     'beacon': "weaviate://localhost/e5dc4a4c-ef0f-3aed-89a3-a73435c6bbcf"
...     'certainty': 0.7 # Optional
... }
Returns

Updated GetBuilder.

Return type

weaviate.gql.get.GetBuilder

Raises

AttributeError – If another ‘near’ filter was already set.

with_near_text(content: dict)weaviate.gql.get.GetBuilder

Set nearText filter. This filter can be used with text modules (text2vec). E.g.: text2vec-contextionary, text2vec-transformers.

Parameters

content (dict) – The content of the nearText filter to set. See examples below.

Examples

Content full prototype:

>>> content = {
...     'concepts': <list of str or str>,
...     'certainty': <float>, # Optional
...     'moveAwayFrom': { # Optional
...         'concepts': <list of str or str>,
...         'force': <float>
...     },
...     'moveTo': { # Optional
...         'concepts': <list of str or str>,
...         'force': <float>
...     }
... }

Full content:

>>> content = {
...     'concepts': ["fashion"],
...     'certainty': 0.7,
...     'moveAwayFrom': {
...         'concepts': ["finance"],
...         'force': 0.45
...     },
...     'moveTo': {
...         'concepts': ["haute couture"],
...         'force': 0.85
...     }
... }

Partial content:

>>> content = {
...     'concepts': ["fashion"],
...     'certainty': 0.7,
...     'moveTo': {
...         'concepts': ["haute couture"],
...         'force': 0.85
...     }
... }

Minimal content:

>>> content = {
...     'concepts': "fashion"
... }
Returns

Updated GetBuilder.

Return type

weaviate.gql.get.GetBuilder

Raises

AttributeError – If another ‘near’ filter was already set.

with_near_vector(content: dict)weaviate.gql.get.GetBuilder

Set nearVector filter.

Parameters

content (dict) – The content of the nearVector filter to set. See examples below.

Examples

Content full prototype:

>>> content = {
...     'vector' : <list of float>,
...     'certainty': <float> # Optional
... }
NOTE: Supported types for ‘vector’ are list, ‘numpy.ndarray`, torch.Tensor

and tf.Tensor.

Full content:

>>> content = {
...     'vector' : [.1, .2, .3, .5],
...     'certainty': 0.75
... }

Minimal content:

>>> content = {
...     'vector' : [.1, .2, .3, .5]
... }

Or

>>> content = {
...     'vector' : torch.tensor([.1, .2, .3, .5])
... }

Or

>>> content = {
...     'vector' : torch.tensor([[.1, .2, .3, .5]]) # it is going to be squeezed.
... }
Returns

Updated GetBuilder.

Return type

weaviate.gql.get.GetBuilder

Raises

AttributeError – If another ‘near’ filter was already set.

with_where(content: dict)weaviate.gql.get.GetBuilder

Set where filter.

Parameters

content (dict) – The content of the where filter to set. See examples below.

Examples

The content prototype is like this:

>>> content = {
...     'operator': '<operator>',
...     'operands': [
...         {
...             'path': [path],
...             'operator': '<operator>'
...             '<valueType>': <value>
...         },
...         {
...             'path': [<matchPath>],
...             'operator': '<operator>',
...             '<valueType>': <value>
...         }
...     ]
... }

This is a complete where filter but it does not have to be like this all the time.

Single operand:

>>> content = {
...     'path': ["wordCount"],    # Path to the property that should be used
...     'operator': 'GreaterThan',  # operator
...     'valueInt': 1000       # value (which is always = to the type of the path property)
... }

Or

>>> content = {
...     'path': ["id"],
...     'operator': 'Equal',
...     'valueString': "e5dc4a4c-ef0f-3aed-89a3-a73435c6bbcf"
... }

Multiple operands:

>>> content = {
...     'operator': 'And',
...     'operands': [
...         {
...             'path': ["wordCount"],
...             'operator': 'GreaterThan',
...             'valueInt': 1000
...         },
...         {
...             'path': ["wordCount"],
...             'operator': 'LessThan',
...             'valueInt': 1500
...         }
...     ]
... }
Returns

Updated GetBuilder.

Return type

weaviate.gql.get.GetBuilder