If the results returned from a Retrieve operation call contain a large amount of irrelevant information, you can pass the SearchFilters parameter in the request to set custom retrieval conditions. This parameter filters the semantic search results to exclude information that is unrelated to the query. This method is especially suitable for structured data.
For more information, see the Retrieve API of the knowledge base.
Comparison
Call the Retrieve operation (without SearchFilters) | Call the Retrieve operation (with SearchFilters) |
Retrieve request body: | Retrieve request body: |
Retrieve response:
Traditional semantic retrieval returns text segments that are not highly relevant to the query "San Zhang". | Retrieve response:
SearchFilters filters out text segments from the semantic search results that are irrelevant to the query "San Zhang". |
Syntax
SearchFilters can contain one or more subgroups. The following example contains two subgroups. Each subgroup consists of one or more key-value pairs (retrieval field: field value) that are used to further filter the text segments retrieved based on the user prompt. By default, AND semantics are applied between subgroups, and this behavior cannot be changed. For more information about how to use subgroups, see Subgroup Query Examples.
{
"searchFilters": [
{
"Name": "San Zhang",
"Sex": "Male"
},
{
"Position": "Engineer"
}
]
}The retrieval fields within a subgroup support single-value queries, multi-value queries, range queries, fuzzy queries, and tag queries.
Single-value query: The field type supports only numeric values (long or double) and strings. For more information, see Single-value query examples.
Multi-value query: Supports only arrays that contain either all numeric values (long or double) or all string values (string). To learn how to use multi-value queries, see Multi-value query examples.
Range query: Supports equality queries and interval queries. For more information, see Range query examples.
Equality query: Supports the
eq(equal to) andneq(not equal to) properties. The field type can be numeric (long or double) or string. You cannot configure multiple values for a single field. The values are case-insensitive.Interval query: Supports the
gt(greater than),gte(greater than or equal to),lt(less than), andlte(less than or equal to) properties. The field type can be only numeric (long or double).
Fuzzy query: The field type supports only strings. The
likeproperty is supported. For more information, see Fuzzy Query Examples.Tag query: Supported only for document search knowledge bases. For more information about how to use tag queries, see Tag query examples.
Prerequisites
Before you can use the Alibaba Cloud API to manage knowledge bases, a RAM user must obtain the AliyunBailianDataFullAccess policy and become member of a workspace. This is not required for an Alibaba Cloud account.
A RAM user can manage only the knowledge bases in the workspaces that the RAM user has joined. An Alibaba Cloud account can manage the knowledge bases in all workspaces.
Install the GenAI service platform SDK and configure the environment.
Obtain and configure an AccessKey and AccessKey secret as environment variables.
Prepare the EmployeeInformation.xlsx file, which contains three records, to create a knowledge base for the following examples. For more information, see Create and use a knowledge base.
Knowledge base configuration:
Knowledge base type: Data Query
Data source: Upload Data Table
Data table field structure: Name, Sex, Position (string type), and Age (double type)
Index settings: All fields are used for retrieval and model responses

Complete code examples
Expand the following panels to view the complete Python and Java code examples provided in this topic. You can implement the code for other languages based on these examples.
Before you call the sample code, you must obtain an AccessKey and AccessKey secret and configure them as environment variables.
Python
SearchFiltersFullExample.py
# The sample code is for reference only. Do not use it in a production environment.
import json
import os
import sys
from typing import List
from alibabacloud_bailian20231229 import models as bailian_20231229_models
from alibabacloud_bailian20231229.client import Client as bailian20231229Client
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_tea_util.client import Client as UtilClient
class SearchFiltersFullExample:
class QueryObject:
def __init__(self, prefix):
self.like = prefix
def to_dict(self):
return {
"like": self.like
}
class Range:
def __init__(self, gte, lte):
self.gte = gte
self.lte = lte
def to_dict(self):
return {
"gte": self.gte,
"lte": self.lte
}
def __init__(self):
pass
@staticmethod
def create_client() -> bailian20231229Client:
"""
Initializes a client using an AccessKey pair.
@return: Client
@throws Exception
"""
# Leaking code that contains an AccessKey pair threatens the security of all resources in your account. The following sample code is for reference only.
# We recommend that you use a more secure method, such as Security Token Service (STS), to manage access credentials. For more information, see https://www.alibabacloud.com/help/sdk/developer-reference/v2-manage-access-credentials.
config = open_api_models.Config(
# Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set.
access_key_id=os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'],
# Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set.
access_key_secret=os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
)
# For more information about endpoints, see https://www.alibabacloud.com/help/model-studio/api-bailian-2023-12-29-endpoint
config.endpoint = f'bailian.ap-southeast-1.aliyuncs.com'
return bailian20231229Client(config)
@staticmethod
def sub_group_query() -> None:
try:
client = SearchFiltersFullExample.create_client()
# Create a retrieve_request object.
retrieve_request = bailian_20231229_models.RetrieveRequest()
# Required. You can enter the actual prompt.
retrieve_request.query = 'Employees in the company named San Zhang'
# Required. Enter the actual knowledge base ID.
retrieve_request.index_id = 'Enter the actual knowledge base ID'
# The query property of group 1 is Name and the value is San Zhang. The query property of group 2 is Sex and the value is Female. You can replace them with the actual property and value.
retrieve_request.search_filters = [
{"Name": "San Zhang"},
{"Sex": "Female"}
]
# Perform a retrieval. Enter the workspace ID and the retrieve_request object.
resp = client.retrieve('Enter the actual workspace ID', retrieve_request)
print(UtilClient.to_jsonstring(resp))
except Exception as error:
# This is for demonstration only. Handle exceptions with caution. Do not ignore exceptions in your project.
# Error message
print(error.message)
@staticmethod
def single_query() -> None:
try:
client = SearchFiltersFullExample.create_client()
# Create a retrieve_request object.
retrieve_request = bailian_20231229_models.RetrieveRequest()
# Required. You can enter the actual prompt.
retrieve_request.query = 'Employees in the company named San Zhang'
# Required. Enter the actual knowledge base ID.
retrieve_request.index_id = 'Enter the actual knowledge base ID'
# The property for the single-value query is Name and the value is San Zhang. You can replace them with the actual property and value.
retrieve_request.search_filters = [
{"Name": "San Zhang"}
]
# Perform a retrieval. Enter the workspace ID and the retrieve_request object.
resp = client.retrieve('Enter the actual workspace ID', retrieve_request)
print(UtilClient.to_jsonstring(resp.body))
except Exception as error:
# This is for demonstration only. Handle exceptions with caution. Do not ignore exceptions in your project.
# Error message
print(error.message)
@staticmethod
def multi_query() -> None:
try:
client = SearchFiltersFullExample.create_client()
# Create a retrieve_request object.
retrieve_request = bailian_20231229_models.RetrieveRequest()
# Required. You can enter the actual prompt.
retrieve_request.query = 'All employees in the company'
# Required. Enter the actual knowledge base ID.
retrieve_request.index_id = 'Enter the actual knowledge base ID'
# Create a list to store multiple values.
names = ["San Zhang", "Si Li"]
# The property for the multi-value query is Name, which corresponds to the names list. The values are the specified "San Zhang" and "Si Li". You can replace them with the actual property and values.
retrieve_request.search_filters = [{"Name": json.dumps(names)}]
# Perform a retrieval. Enter the workspace ID and the retrieve_request object.
resp = client.retrieve('Enter the actual workspace ID', retrieve_request)
print(UtilClient.to_jsonstring(resp.body))
except Exception as error:
# This is for demonstration only. Handle exceptions with caution. Do not ignore exceptions in your project.
# Error message
print(error.message)
@staticmethod
def range_query() -> None:
try:
client = SearchFiltersFullExample.create_client()
# Create a retrieve_request object.
retrieve_request = bailian_20231229_models.RetrieveRequest()
# Required. You can enter the actual prompt.
retrieve_request.query = 'All employees in the company'
# Required. Enter the actual knowledge base ID.
retrieve_request.index_id = 'Enter the actual knowledge base ID'
# The query property is Age and the value is a range. You can replace them with the actual property and value.
age_range = SearchFiltersFullExample.Range(20, 27)
retrieve_request.search_filters = [
{"Position": "Engineer"}, # Group 1: Position filter condition
{"Age": json.dumps(age_range.to_dict())} # Group 2: Age range filter condition
]
# Perform a retrieval. Enter the workspace ID and the retrieve_request object.
resp = client.retrieve('Enter the actual workspace ID', retrieve_request)
print(UtilClient.to_jsonstring(resp.body))
except Exception as error:
# This is for demonstration only. Handle exceptions with caution. Do not ignore exceptions in your project.
# Error message
print(error.message)
@staticmethod
def wildcard_query() -> None:
try:
client = SearchFiltersFullExample.create_client()
# Create a retrieve_request object.
retrieve_request = bailian_20231229_models.RetrieveRequest()
# Required. You can enter the actual prompt.
retrieve_request.query = 'Male employees in the company'
# Required. Enter the actual knowledge base ID.
retrieve_request.index_id = 'Enter the actual knowledge base ID'
# The property for the fuzzy query is Position and the value is E%r. The % wildcard character matches any string of zero or more characters. You can replace it with the actual value.
position = SearchFiltersFullExample.QueryObject('E%r')
retrieve_request.search_filters = [
{"Name": "San Zhang"}, # Name filter condition. You can replace it with the actual property and value.
{"Position": json.dumps(position.to_dict())} # Position (fuzzy query) filter condition. You can replace it with the actual property and value.
]
# Perform a retrieval. Enter the workspace ID and the retrieve_request object.
resp = client.retrieve('Enter the actual workspace ID', retrieve_request)
print(UtilClient.to_jsonstring(resp.body))
except Exception as error:
# This is for demonstration only. Handle exceptions with caution. Do not ignore exceptions in your project.
# Error message
print(error.message)
@staticmethod
def tag_query() -> None:
try:
client = SearchFiltersFullExample.create_client()
# Create a retrieve_request object.
retrieve_request = bailian_20231229_models.RetrieveRequest()
# Required. You can enter the actual prompt.
retrieve_request.query = 'Provide some candidates'
# Required. Enter the actual knowledge base ID.
retrieve_request.index_id = 'Enter the actual knowledge base ID'
# Create a list to store tags. The logical relationship between multiple tags is OR, not AND.
tags = ["University A", "Student Union President"]
retrieve_request.search_filters = [
{"tags": json.dumps(tags)}
]
# Perform a retrieval. Enter the workspace ID and the retrieve_request object.
resp = client.retrieve('Enter the actual workspace ID', retrieve_request)
print(UtilClient.to_jsonstring(resp.body))
except Exception as error:
# This is for demonstration only. Handle exceptions with caution. Do not ignore exceptions in your project.
# Error message
print(error.message)
@staticmethod
def tag_query2() -> None:
try:
client = SearchFiltersFullExample.create_client()
# Create a retrieve_request object.
retrieve_request = bailian_20231229_models.RetrieveRequest()
# Required. You can enter the actual prompt.
retrieve_request.query = 'Provide some candidates'
# Required. Enter the actual knowledge base ID.
retrieve_request.index_id = 'Enter the actual knowledge base ID'
# Create two lists to store tags.
tag1 = ["University A"]
tag2 = ["Sports Specialist Student"]
retrieve_request.search_filters = [
{"tags": json.dumps(tag1)},
{"tags": json.dumps(tag2)}
]
# Perform a retrieval. Enter the workspace ID and the retrieve_request object.
resp = client.retrieve('Enter the actual workspace ID', retrieve_request)
print(UtilClient.to_jsonstring(resp.body))
except Exception as error:
# This is for demonstration only. Handle exceptions with caution. Do not ignore exceptions in your project.
# Error message
print(error.message)
@staticmethod
def main(args: List[str]) -> None:
SearchFiltersFullExample.sub_group_query()
SearchFiltersFullExample.single_query()
SearchFiltersFullExample.multi_query()
SearchFiltersFullExample.range_query()
SearchFiltersFullExample.wildcard_query()
SearchFiltersFullExample.tag_query()
SearchFiltersFullExample.tag_query2()
if __name__ == '__main__':
SearchFiltersFullExample.main(sys.argv[1:])Java
SearchFiltersFullExample.java
// The sample code is for reference only. Do not use it in a production environment.
import com.aliyun.bailian20231229.models.RetrieveRequest;
import com.aliyun.bailian20231229.models.RetrieveResponse;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class SearchFiltersFullExample {
/**
* descriptionGetting started
The following sections describe how to use SearchFilters for queries.
Subgroup query examples
Subgroups are used to filter the retrieval results of a knowledge base and return only the text segments that meet specific conditions. You can add multiple subgroups (conditions) to SearchFilters. By default, the subgroups are combined using the AND operator, and this behavior cannot be changed.
Example: Retrieve the employee information knowledge base and filter for records where the Name is San Zhang and the Sex is Female. No such record exists in this knowledge base.
{
"searchFilters": [
{
"Name": "San Zhang"
},
{
"Sex": "Female"
}
]
}Expand the following panels to view the sample code.
Python
SubGroupQueryExample.py
# The sample code is for reference only. Do not use it in a production environment.
import os
import sys
from typing import List
from alibabacloud_bailian20231229 import models as bailian_20231229_models
from alibabacloud_bailian20231229.client import Client as bailian20231229Client
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_tea_util.client import Client as UtilClient
class SubGroupQueryExample:
def __init__(self):
pass
@staticmethod
def create_client() -> bailian20231229Client:
"""
Initializes a client using an AccessKey pair.
@return: Client
@throws Exception
"""
# Leaking code that contains an AccessKey pair threatens the security of all resources in your account. The following sample code is for reference only.
# We recommend that you use a more secure method, such as Security Token Service (STS), to manage access credentials. For more information, see https://www.alibabacloud.com/help/sdk/developer-reference/v2-manage-access-credentials.
config = open_api_models.Config(
# Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set.
access_key_id=os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'],
# Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set.
access_key_secret=os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
)
# For more information about endpoints, see https://www.alibabacloud.com/help/model-studio/api-bailian-2023-12-29-endpoint
config.endpoint = f'bailian.ap-southeast-1.aliyuncs.com'
return bailian20231229Client(config)
@staticmethod
def main(
args: List[str],
) -> None:
try:
client = SubGroupQueryExample.create_client()
# Create a retrieve_request object.
retrieve_request = bailian_20231229_models.RetrieveRequest()
# Required. You can enter the actual prompt.
retrieve_request.query = 'Employees in the company named San Zhang'
# Required. Enter the actual knowledge base ID.
retrieve_request.index_id = 'Enter the actual knowledge base ID'
# The query property of group 1 is Name and the value is San Zhang. The query property of group 2 is Sex and the value is Female. You can replace them with the actual property and value.
retrieve_request.search_filters = [
{"Name": "San Zhang"},
{"Sex": "Female"}
]
# Perform a retrieval. Enter the workspace ID and the retrieve_request object.
resp = client.retrieve('Enter the actual workspace ID', retrieve_request)
print(UtilClient.to_jsonstring(resp))
except Exception as error:
# This is for demonstration only. Handle exceptions with caution. Do not ignore exceptions in your project.
# Error message
print(error.message)
if __name__ == '__main__':
SubGroupQueryExample.main(sys.argv[1:])
Sample request
{
"indexId": "27ubwxxxxx",
"WorkspaceId":"llm-4u5xpd1xdjxxxxxx",
"query": "Employees in the company named San Zhang",
"searchFilters": [
{
"Name": "San Zhang"
},
{
"Sex": "Female"
}
]
}Sample response
{
"code": "Success",
"data": {
"nodes": []
},
"message": "success",
"requestId": "5BA30772-xxxx-560C-B1F7-C1DA737A9D80",
"status": "200",
"success": true
}Java
SubGroupQueryExample.java
// The sample code is for reference only. Do not use it in a production environment.
import com.aliyun.bailian20231229.models.RetrieveRequest;
import com.aliyun.bailian20231229.models.RetrieveResponse;
import com.google.gson.Gson;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class SubGroupQueryExample {
/**
* descriptionSample request
{
"indexId": "27ubwxxxxx",
"WorkspaceId":"llm-4u5xpd1xdjxxxxxx",
"query": "Employees in the company named San Zhang",
"searchFilters": [
{
"Name": "San Zhang"
},
{
"Sex": "Female"
}
]
}Sample response
{
"code": "Success",
"data": {
"nodes": []
},
"message": "success",
"requestId": "5BA30772-xxxx-560C-B1F7-C1DA737A9D80",
"status": "200",
"success": true
}Single-value query examples
In a single-value query, you pass a single value for the retrieval field.
Example: Retrieve the employee information knowledge base and filter for records where the Name is San Zhang.
{
"searchFilters": [
{
"Name": "San Zhang"
}
]
}Expand the following panels to view the sample code.
Python
SingleQueryExample.py
# The sample code is for reference only. Do not use it in a production environment.
import os
import sys
from typing import List
from alibabacloud_bailian20231229 import models as bailian_20231229_models
from alibabacloud_bailian20231229.client import Client as bailian20231229Client
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_tea_util.client import Client as UtilClient
class SingleQueryExample:
def __init__(self):
pass
@staticmethod
def create_client() -> bailian20231229Client:
"""
Initializes a client using an AccessKey pair.
@return: Client
@throws Exception
"""
# Leaking code that contains an AccessKey pair threatens the security of all resources in your account. The following sample code is for reference only.
# We recommend that you use a more secure method, such as Security Token Service (STS), to manage access credentials. For more information, see https://www.alibabacloud.com/help/sdk/developer-reference/v2-manage-access-credentials.
config = open_api_models.Config(
# Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set.
access_key_id=os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'],
# Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set.
access_key_secret=os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
)
# For more information about endpoints, see https://www.alibabacloud.com/help/model-studio/api-bailian-2023-12-29-endpoint
config.endpoint = f'bailian.ap-southeast-1.aliyuncs.com'
return bailian20231229Client(config)
@staticmethod
def main(
args: List[str],
) -> None:
client = SingleQueryExample.create_client()
# Create a retrieve_request object.
retrieve_request = bailian_20231229_models.RetrieveRequest()
# Required. You can enter the actual prompt.
retrieve_request.query = 'Employees in the company named San Zhang'
# Required. Enter the actual knowledge base ID.
retrieve_request.index_id = 'Enter the actual knowledge base ID'
# The property for the single-value query is Name and the value is San Zhang. You can replace them with the actual property and value.
retrieve_request.search_filters = [
{"Name": "San Zhang"}
]
try:
# Perform a retrieval. Enter the workspace ID and the retrieve_request object.
resp = client.retrieve('Enter the actual workspace ID', retrieve_request)
print(UtilClient.to_jsonstring(resp.body))
except Exception as error:
# This is for demonstration only. Handle exceptions with caution. Do not ignore exceptions in your project.
# Error message
print(error.message)
if __name__ == '__main__':
SingleQueryExample.main(sys.argv[1:])
Sample request
{
"indexId": "27ubwxxxxx",
"WorkspaceId":"llm-4u5xpd1xdjxxxxxx",
"query": "Employees in the company named San Zhang",
"searchFilters": [
{
"Name": "San Zhang"
}
]
}Sample response
{
"code": "Success",
"data": {
"nodes": [
{
"metadata": {
"_rc_v_score": 0.32581159472465515,
"_q_score": 1,
"source": "0",
"_score": 0.4556944966316223,
"doc_id": "table_xxxx75507aab4bd9a24c18d098b2e8ac_10285263_1",
"Sex": "Male",
"_rc_score": 0,
"Name": "San Zhang",
"doc_name": "Employee Sheet",
"_id": "llm-xxxxpd1xdjqp8itj_27ubwxxxxx_table_200275507aab4bd9a24c18d098b2e8ac_10285263_1",
"Age": "25",
"Position": "Engineer"
},
"score": 0.4556944966316223,
"text": "Name:San Zhang Age:25 Position:Engineer Sex:Male"
}
]
},
"message": "success",
"requestId": "2FA4113E-xxxx-59C1-BDB2-5B930D8C9B1C",
"status": "200",
"success": true
}Java
SingleQueryExample.java
// The sample code is for reference only. Do not use it in a production environment.
import com.aliyun.bailian20231229.models.RetrieveRequest;
import com.aliyun.bailian20231229.models.RetrieveResponse;
import com.google.gson.Gson;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class SingleQueryExample {
/**
* descriptionSample request
{
"indexId": "27ubwxxxxx",
"WorkspaceId":"llm-4u5xpd1xdjxxxxxx",
"query": "Employees in the company named San Zhang",
"searchFilters": [
{
"Name": "San Zhang"
}
]
}Sample response
{
"code": "Success",
"data": {
"nodes": [
{
"metadata": {
"_rc_v_score": 0.32581159472465515,
"_q_score": 1,
"source": "0",
"_score": 0.4556944966316223,
"doc_id": "table_xxxx75507aab4bd9a24c18d098b2e8ac_10285263_1",
"Sex": "Male",
"_rc_score": 0,
"Name": "San Zhang",
"doc_name": "Employee Sheet",
"_id": "llm-xxxxpd1xdjqp8itj_27ubwxxxxx_table_xxxx75507aab4bd9a24c18d098b2e8ac_10285263_1",
"Age": "25",
"Position": "Engineer"
},
"score": 0.4556944966316223,
"text": "Name:San Zhang Age:25 Position:Engineer Sex:Male"
}
]
},
"message": "success",
"requestId": "2FA4113E-xxxx-59C1-BDB2-5B930D8C9B1C",
"status": "200",
"success": true
}Multi-value query examples
A multi-value query lets you pass multiple values for a retrieval field, similar to the IN operator in SQL.
Example: Retrieve the employee information knowledge base and filter for records where the Name is San Zhang or Si Li.
{
"searchFilters": [
{
"Name": "["San Zhang","Si Li"]"
}
]
}Expand the following panels to view the sample code.
Python
MultiQueryExample.py
# The sample code is for reference only. Do not use it in a production environment.
import json
import os
import sys
from typing import List
from alibabacloud_bailian20231229 import models as bailian_20231229_models
from alibabacloud_bailian20231229.client import Client as bailian20231229Client
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_tea_util.client import Client as UtilClient
class MultiQueryExample:
def __init__(self):
pass
@staticmethod
def create_client() -> bailian20231229Client:
"""
Initializes a client using an AccessKey pair.
@return: Client
@throws Exception
"""
# Leaking code that contains an AccessKey pair threatens the security of all resources in your account. The following sample code is for reference only.
# We recommend that you use a more secure method, such as Security Token Service (STS), to manage access credentials. For more information, see https://www.alibabacloud.com/help/sdk/developer-reference/v2-manage-access-credentials.
config = open_api_models.Config(
# Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set.
access_key_id=os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'],
# Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set.
access_key_secret=os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
)
# For more information about endpoints, see https://www.alibabacloud.com/help/model-studio/api-bailian-2023-12-29-endpoint
config.endpoint = f'bailian.ap-southeast-1.aliyuncs.com'
return bailian20231229Client(config)
@staticmethod
def main(
args: List[str],
) -> None:
try:
client = MultiQueryExample.create_client()
# Create a retrieve_request object.
retrieve_request = bailian_20231229_models.RetrieveRequest()
# Required. You can enter the actual prompt.
retrieve_request.query = 'All employees in the company'
# Required. Enter the actual knowledge base ID.
retrieve_request.index_id = 'Enter the actual knowledge base ID'
# Create a list to store multiple values.
names = ["San Zhang", "Si Li"]
# The property for the multi-value query is Name, which corresponds to the names list. The values are the specified "San Zhang" and "Si Li". You can replace them with the actual property and values.
retrieve_request.search_filters = [{"Name": json.dumps(names)}]
# Perform a retrieval. Enter the workspace ID and the retrieve_request object.
resp = client.retrieve('Enter the actual workspace ID', retrieve_request)
print(UtilClient.to_jsonstring(resp.body))
except Exception as error:
# This is for demonstration only. Handle exceptions with caution. Do not ignore exceptions in your project.
# Error message
print(error.message)
if __name__ == '__main__':
MultiQueryExample.main(sys.argv[1:])Sample request
{
"indexId": "27ubwxxxxx",
"WorkspaceId":"llm-4u5xpd1xdjxxxxxx",
"query": "All employees in the company",
"searchFilters": [
{
"Name": "[\"San Zhang\",\"Si Li\"]"
}
]
}Sample response
{
"code": "Success",
"data": {
"nodes": [
{
"metadata": {
"_rc_v_score": 0.3016361088048254,
"_q_score": 1,
"source": "0",
"_score": 0.3322954773902893,
"doc_id": "table_xxxxad1c331c424780a8023376a73fac_10285263_1",
"Sex": "Male",
"_rc_score": 0,
"Name": "San Zhang",
"doc_name": "Employee Sheet",
"_id": "llm-xxxxpd1xdjqp8itj_27ubwxxxxx_table_xxxxad1c331c424780a8023376a73fac_10285263_1",
"Age": "25.0",
"Position": "Engineer"
},
"score": 0.3322954773902893,
"text": "Name:San Zhang Age:25.0 Position:Engineer Sex:Male"
},
{
"metadata": {
"_rc_v_score": 0.2531493306159973,
"_q_score": 0.8392540654998252,
"source": "0",
"_score": 0.25632044672966003,
"doc_id": "table_xxxxad1c331c424780a8023376a73fac_10285263_2",
"Sex": "Female",
"_rc_score": 0,
"Name": "Si Li",
"doc_name": "Employee Sheet",
"_id": "llm-xxxxpd1xdjqp8itj_27ubwxxxxx_table_xxxxad1c331c424780a8023376a73fac_10285263_2",
"Age": "31.0",
"Position": "Sales"
},
"score": 0.25632044672966003,
"text": "Name:Si Li Age:31.0 Position:Sales Sex:Female"
}
]
},
"message": "success",
"requestId": "1DFE5E9E-xxxx-5C37-8011-8FA2E2875309",
"status": "200",
"success": true
}Java
MultiQueryExample.java
// The sample code is for reference only. Do not use it in a production environment.
import com.aliyun.bailian20231229.models.RetrieveRequest;
import com.aliyun.bailian20231229.models.RetrieveResponse;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MultiQueryExample {
/**
* descriptionSample request
{
"indexId": "27ubwxxxxx",
"WorkspaceId":"llm-4u5xpd1xdjxxxxxx",
"query": "All employees in the company",
"searchFilters": [
{
"Name": "[\"San Zhang\",\"Si Li\"]"
}
]
}Sample response
{
"code": "Success",
"data": {
"nodes": [
{
"metadata": {
"_rc_v_score": 0.3016361088048254,
"_q_score": 1,
"source": "0",
"_score": 0.3322954773902893,
"doc_id": "table_xxxxad1c331c424780a8023376a73fac_10285263_1",
"Sex": "Male",
"_rc_score": 0,
"Name": "San Zhang",
"doc_name": "Employee Sheet",
"_id": "llm-xxxxpd1xdjqp8itj_27ubwxxxxx_table_xxxxad1c331c424780a8023376a73fac_10285263_1",
"Age": "25.0",
"Position": "Engineer"
},
"score": 0.3322954773902893,
"text": "Name:San Zhang Age:25.0 Position:Engineer Sex:Male"
},
{
"metadata": {
"_rc_v_score": 0.2531493306159973,
"_q_score": 0.8392540654998252,
"source": "0",
"_score": 0.25632044672966003,
"doc_id": "table_xxxxad1c331c424780a8023376a73fac_10285263_2",
"Sex": "Female",
"_rc_score": 0,
"Name": "Si Li",
"doc_name": "Employee Sheet",
"_id": "llm-xxxxpd1xdjqp8itj_27ubwxxxxx_table_xxxxad1c331c424780a8023376a73fac_10285263_2",
"Age": "31.0",
"Position": "Sales"
},
"score": 0.25632044672966003,
"text": "Name:Si Li Age:31.0 Position:Sales Sex:Female"
}
]
},
"message": "success",
"requestId": "1DFE5E9E-xxxx-5C37-8011-8FA2E2875309",
"status": "200",
"success": true
}Range query examples
You can use a range query to find all records where the value of a retrieval field, such as age, falls within a specified range.
Example: Retrieve the employee information knowledge base and filter for records where the Position is Engineer (single-value query) and the Age is between 20 and 25 (range query).
{
"searchFilters": [
{
"Position": "Engineer"
},
{
"Age": {
"gte": 20,
"lte": 25
}
}
]
}Expand the following panels to view the sample code.
Python
RangeQueryExample.py
# The sample code is for reference only. Do not use it in a production environment.
import json
import os
import sys
from typing import List
from alibabacloud_bailian20231229 import models as bailian_20231229_models
from alibabacloud_bailian20231229.client import Client as bailian20231229Client
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_tea_util.client import Client as UtilClient
class RangeQueryExample:
class Range:
def __init__(self, gte, lte):
self.gte = gte
self.lte = lte
def to_dict(self):
return {
"gte": self.gte,
"lte": self.lte
}
def __init__(self):
pass
@staticmethod
def create_client() -> bailian20231229Client:
"""
Initializes a client using an AccessKey pair.
@return: Client
@throws Exception
"""
# Leaking code that contains an AccessKey pair threatens the security of all resources in your account. The following sample code is for reference only.
# We recommend that you use a more secure method, such as Security Token Service (STS), to manage access credentials. For more information, see https://www.alibabacloud.com/help/sdk/developer-reference/v2-manage-access-credentials.
config = open_api_models.Config(
# Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set.
access_key_id=os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'],
# Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set.
access_key_secret=os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
)
# For more information about endpoints, see https://www.alibabacloud.com/help/model-studio/api-bailian-2023-12-29-endpoint
config.endpoint = f'bailian.ap-southeast-1.aliyuncs.com'
return bailian20231229Client(config)
@staticmethod
def main(
args: List[str],
) -> None:
try:
client = RangeQueryExample.create_client()
# Create a retrieve_request object.
retrieve_request = bailian_20231229_models.RetrieveRequest()
# Required. You can enter the actual prompt.
retrieve_request.query = 'All employees in the company'
# Required. Enter the actual knowledge base ID.
retrieve_request.index_id = 'Enter the actual knowledge base ID'
# The query property is Age and the value is a range. You can replace them with the actual property and value.
age_range = RangeQueryExample.Range(20, 27)
retrieve_request.search_filters = [
{"Position": "Engineer"}, # Group 1: Position filter condition
{"Age": json.dumps(age_range.to_dict())} # Group 2: Age range filter condition
]
# Perform a retrieval. Enter the workspace ID and the retrieve_request object.
resp = client.retrieve('Enter the actual workspace ID', retrieve_request)
print(UtilClient.to_jsonstring(resp.body))
except Exception as error:
# This is for demonstration only. Handle exceptions with caution. Do not ignore exceptions in your project.
# Error message
print(error.message)
if __name__ == '__main__':
RangeQueryExample.main(sys.argv[1:])
Sample request
{
"indexId": "27ubwxxxxx",
"WorkspaceId":"llm-4u5xpd1xdjxxxxxx",
"query": "All employees in the company",
"searchFilters": [
{
"Sex": "Male"
},
{
"Age": "{\"gte\":20.0,\"lte\":27.0}"
}
]
}Sample response
{
"code": "Success",
"data": {
"nodes": [
{
"metadata": {
"_rc_v_score": 0.3016361088048254,
"_q_score": 1,
"source": "0",
"_score": 0.3322954773902893,
"doc_id": "table_xxxxad1c331c424780a8023376a73fac_10285263_1",
"Sex": "Male",
"_rc_score": 0,
"Name": "San Zhang",
"doc_name": "Employee Sheet",
"_id": "llm-xxxxpd1xdjqp8itj_27ubwxxxxx_table_xxxxad1c331c424780a8023376a73fac_10285263_1",
"Age": "25.0",
"Position": "Engineer"
},
"score": 0.3322954773902893,
"text": "Name:San Zhang Age:25.0 Position:Engineer Sex:Male"
}
]
},
"message": "success",
"requestId": "AE0B5ABC-xxxx-54A1-9ED4-91865B859DF6",
"status": "200",
"success": true
}Java
RangeQueryExample.java
// The sample code is for reference only. Do not use it in a production environment.
import com.aliyun.bailian20231229.models.RetrieveRequest;
import com.aliyun.bailian20231229.models.RetrieveResponse;
import com.google.gson.Gson;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class RangeQueryExample {
/**
* descriptionSample request
{
"indexId": "27ubwxxxxx",
"WorkspaceId":"llm-4u5xpd1xdjxxxxxx",
"query": "All employees in the company",
"searchFilters": [
{
"Sex": "Male"
},
{
"Age": "{\"gte\":20.0,\"lte\":27.0}"
}
]
}Sample response
{
"code": "Success",
"data": {
"nodes": [
{
"metadata": {
"_rc_v_score": 0.3016361088048254,
"_q_score": 1,
"source": "0",
"_score": 0.3322954773902893,
"doc_id": "table_xxxxad1c331c424780a8023376a73fac_10285263_1",
"Sex": "Male",
"_rc_score": 0,
"Name": "San Zhang",
"doc_name": "Employee Sheet",
"_id": "llm-xxxxpd1xdjqp8itj_27ubwxxxxx_table_xxxxad1c331c424780a8023376a73fac_10285263_1",
"Age": "25.0",
"Position": "Engineer"
},
"score": 0.3322954773902893,
"text": "Name:San Zhang Age:25.0 Position:Engineer Sex:Male"
}
]
},
"message": "success",
"requestId": "AE0B5ABC-xxxx-54A1-9ED4-91865B859DF6",
"status": "200",
"success": true
}Fuzzy query examples
A fuzzy query uses wildcard characters to find records that contain a specific sequence of characters, similar to the LIKE operator in SQL.
The fuzzy query in SearchFilters supports the following wildcard characters, which are consistent with SQL syntax:
Wildcard character | Description |
% | Replaces zero or more characters. |
_ | Replaces a single character. |
Example: Retrieve the employee information knowledge base and filter for records where the Name is San Zhang and the Position contains a value that starts with E and ends with r, such as Engineer.
{
"searchFilters": [
{
"Name": "San Zhang"
},
{
"Position": {
"like": "E%r"
}
}
]
}Expand the following panels to view the sample code.
Python
WildcardQueryExample.py
# The sample code is for reference only. Do not use it in a production environment.
import json
import os
import sys
from typing import List
from alibabacloud_bailian20231229 import models as bailian_20231229_models
from alibabacloud_bailian20231229.client import Client as bailian20231229Client
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_tea_util.client import Client as UtilClient
class WildcardQueryExample:
class QueryObject:
def __init__(self, prefix):
self.like = prefix
def to_dict(self):
return {
"like": self.like
}
def __init__(self):
pass
@staticmethod
def create_client() -> bailian20231229Client:
"""
Initializes a client using an AccessKey pair.
@return: Client
@throws Exception
"""
# Leaking code that contains an AccessKey pair threatens the security of all resources in your account. The following sample code is for reference only.
# We recommend that you use a more secure method, such as Security Token Service (STS), to manage access credentials. For more information, see https://www.alibabacloud.com/help/sdk/developer-reference/v2-manage-access-credentials.
config = open_api_models.Config(
# Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set.
access_key_id=os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'],
# Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set.
access_key_secret=os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
)
# For more information about endpoints, see https://www.alibabacloud.com/help/model-studio/api-bailian-2023-12-29-endpoint
config.endpoint = f'bailian.ap-southeast-1.aliyuncs.com'
return bailian20231229Client(config)
@staticmethod
def main(
args: List[str],
) -> None:
try:
client = WildcardQueryExample.create_client()
# Create a retrieve_request object.
retrieve_request = bailian_20231229_models.RetrieveRequest()
# Required. You can enter the actual prompt.
retrieve_request.query = 'Male employees in the company'
# Required. Enter the actual knowledge base ID.
retrieve_request.index_id = 'Enter the actual knowledge base ID'
# The property for the fuzzy query is Position and the value is E%r. The % wildcard character matches any string of zero or more characters. You can replace it with the actual value.
position = WildcardQueryExample.QueryObject('E%r')
retrieve_request.search_filters = [
{"Name": "San Zhang"}, # Name filter condition. You can replace it with the actual property and value.
{"Position": json.dumps(position.to_dict())} # Position (fuzzy query) filter condition. You can replace it with the actual property and value.
]
# Perform a retrieval. Enter the workspace ID and the retrieve_request object.
resp = client.retrieve('Enter the actual workspace ID', retrieve_request)
print(UtilClient.to_jsonstring(resp.body))
except Exception as error:
# This is for demonstration only. Handle exceptions with caution. Do not ignore exceptions in your project.
# Error message
print(error.message)
if __name__ == '__main__':
WildcardQueryExample.main(sys.argv[1:])
Sample request
{
"indexId": "27ubwxxxxx",
"WorkspaceId":"llm-4u5xpd1xdjxxxxxx",
"query": "Male employees in the company",
"searchFilters": [
{
"Name": "San Zhang"
},
{
"Position": "{\"like\":\"E%r\"}"
}
]
}Sample response
{
"code": "Success",
"data": {
"nodes": [
{
"metadata": {
"_rc_v_score": 0.41137335930387275,
"_q_score": 1,
"source": "0",
"_score": 0.46098726987838745,
"doc_id": "table_xxxxad1c331c424780a8023376a73fac_10285263_1",
"Sex": "Male",
"_rc_score": 0,
"Name": "San Zhang",
"doc_name": "Employee Sheet",
"_id": "llm-xxxxpd1xdjqp8itj_27ubwxxxxx_table_xxxxad1c331c424780a8023376a73fac_10285263_1",
"Age": "25.0",
"Position": "Engineer"
},
"score": 0.46098726987838745,
"text": "Name:San Zhang Age:25.0 Position:Engineer Sex:Male"
}
]
},
"message": "success",
"requestId": "FA759FEC-xxxx-50B7-A64D-BE49A7DF56B8",
"status": "200",
"success": true
}Java
WildcardQueryExample.java
// The sample code is for reference only. Do not use it in a production environment.
import com.aliyun.bailian20231229.models.RetrieveRequest;
import com.aliyun.bailian20231229.models.RetrieveResponse;
import com.google.gson.Gson;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class WildcardQueryExample {
/**
* descriptionSample request
{
"indexId": "27ubwxxxxx",
"WorkspaceId":"llm-4u5xpd1xdjxxxxxx",
"query": "Male employees in the company",
"searchFilters": [
{
"Name": "San Zhang"
},
{
"Position": "{\"like\":\"E%r\"}"
}
]
}Sample response
{
"code": "Success",
"data": {
"nodes": [
{
"metadata": {
"_rc_v_score": 0.41137335930387275,
"_q_score": 1,
"source": "0",
"_score": 0.46098726987838745,
"doc_id": "table_xxxxad1c331c424780a8023376a73fac_10285263_1",
"Sex": "Male",
"_rc_score": 0,
"Name": "San Zhang",
"doc_name": "Employee Sheet",
"_id": "llm-xxxxpd1xdjqp8itj_27ubwxxxxx_table_xxxxad1c331c424780a8023376a73fac_10285263_1",
"Age": "25.0",
"Position": "Engineer"
},
"score": 0.46098726987838745,
"text": "Name:San Zhang Age:25.0 Position:Engineer Sex:Male"
}
]
},
"message": "success",
"requestId": "FA759FEC-xxxx-50B7-A64D-BE49A7DF56B8",
"status": "200",
"success": true
}Tag query examples
When you search a document search knowledge base, you can filter files using tags to improve retrieval efficiency and accuracy.
Example: Create a document search knowledge base that contains information about three individuals: San Zhang, Si Li, and Wu Wang.

The preceding files have the following tags:
File | Tag |
San Zhang's Resume |
|
Si Li's Resume |
|
Wu Wang's Resume |
|
For example, you can use SearchFilters to query the talent knowledge base and return text segments from files that have the tag University A or Student Union President:
A logical OR relationship exists between multiple tags, not a logical AND relationship. You can use subgroup queries to implement a logical AND.
{
"searchFilters": [
{
"tags": "["University A","Student Union President"]"
}
]
}Expand the following panels to view the sample code.
Python
TagQueryExample.py
# The sample code is for reference only. Do not use it in a production environment.
import json
import os
import sys
from typing import List
from alibabacloud_bailian20231229 import models as bailian_20231229_models
from alibabacloud_bailian20231229.client import Client as bailian20231229Client
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_tea_util.client import Client as UtilClient
class TagQueryExample:
def __init__(self):
pass
@staticmethod
def create_client() -> bailian20231229Client:
"""
Initializes a client using an AccessKey pair.
@return: Client
@throws Exception
"""
# Leaking code that contains an AccessKey pair threatens the security of all resources in your account. The following sample code is for reference only.
# We recommend that you use a more secure method, such as Security Token Service (STS), to manage access credentials. For more information, see https://www.alibabacloud.com/help/zh/sdk/developer-reference/v2-manage-python-access-credentials.
config = open_api_models.Config(
# Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set.
access_key_id=os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'],
# Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set.
access_key_secret=os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
)
# For more information about endpoints, see https://www.alibabacloud.com/help/model-studio/api-bailian-2023-12-29-endpoint
config.endpoint = f'bailian.ap-southeast-1.aliyuncs.com'
return bailian20231229Client(config)
@staticmethod
def main(
args: List[str],
) -> None:
client = TagQueryExample.create_client()
# Create a retrieve_request object.
retrieve_request = bailian_20231229_models.RetrieveRequest()
# Required. You can enter the actual prompt.
retrieve_request.query = 'Provide some candidates'
# Required. Enter the actual knowledge base ID.
retrieve_request.index_id = 'Enter the actual knowledge base ID'
# Create a list to store tags. The logical relationship between multiple tags is OR, not AND.
tags = ["University A", "Student Union President"]
retrieve_request.search_filters = [
{"tags": json.dumps(tags)}
]
try:
# Perform a retrieval. Enter the workspace ID and the retrieve_request object.
resp = client.retrieve('Enter the actual workspace ID', retrieve_request)
print(UtilClient.to_jsonstring(resp.body))
except Exception as error:
# This is for demonstration only. Handle exceptions with caution. Do not ignore exceptions in your project.
# Error message
print(error.message)
if __name__ == '__main__':
TagQueryExample.main(sys.argv[1:])Sample request
{
"IndexId": "8mbtdxxxxx",
"WorkspaceId": "llm-4u5xpd1xdjxxxxxx",
"Query": "Provide some candidates",
"SearchFilters": "[{\"tags\":\"[\\\"University A\\\", \\\"Student Union President\\\"]\"}]"
}Sample response
{
"Code": "Success",
"Data": {
"Nodes": [
{
"Metadata": {
"file_path": "https://bailian-datahub-data-prod.oss-cn-beijing.aliyuncs.com/10285263/multimodal/docJson/Zhang_San_Resume_1746760910599.json?Expires=1747020348&OSSAccessKeyId=LTAI************&Signature=roY%2Falbh6smkLdPuA6wjnZRVMa4%3D",
"is_displayed_chunk_content": "true",
"_rc_v_score": 0.1422617520249937,
"image_url": [],
"nid": "ba8a14099f43308734538c29271cc7cd|b99e98835c3c6d8f6496df5a43de0ba5|aa3ed8fc4aae8bbb78872994b01e0fda",
"_q_score": 0.8935035934804278,
"source": "0",
"_score": 0.1736905574798584,
"title": "",
"doc_id": "file_e787926158704f95aad6bc967619f176_10285263",
"content": "Name: San Zhang Sex: Male Age: 23",
"_rc_score": 0,
"workspace_id": "llm-4u5xpd1xdjxxxxxx",
"hier_title": "",
"page_number": [
0
],
"doc_name": "San Zhang's Resume",
"pipeline_id": "8mbtdxxxxx",
"_id": "llm-4u5xpd1xdjxxxxxx_8mbtdxxxxx_file_e787926158704f95aad6bc967619f176_10285263_0_0"
},
"Score": 0.1736905574798584,
"Text": "Name: San Zhang Sex: Male Age: 23"
},
{
"Metadata": {
"file_path": "https://bailian-datahub-data-prod.oss-cn-beijing.aliyuncs.com/10285263/multimodal/docJson/Wang_Wu_Resume_1746760946844.json?Expires=1747020348&OSSAccessKeyId=LTAI************&Signature=gTGPTce5xUu9mtcMcmyMEeb5azk%3D",
"is_displayed_chunk_content": "true",
"_rc_v_score": 0.1592178845871759,
"image_url": [],
"nid": "ba8a14099f43308734538c29271cc7cd|d4a048b6799ce07e08430f018af091a0|fe90f8248ea64f70ea37c0df7afcfc12",
"_q_score": 1,
"source": "0",
"_score": 0.15737050771713257,
"title": "",
"doc_id": "file_63563df5df66488cb8e28bfff11e40eb_10285263",
"content": "Name: Wu Wang Sex: Male Age: 23",
"_rc_score": 0,
"workspace_id": "llm-4u5xpd1xdjxxxxxx",
"hier_title": "",
"page_number": [
0
],
"doc_name": "Wu Wang's Resume",
"pipeline_id": "8mbtdxxxxx",
"_id": "llm-4u5xpd1xdjxxxxxx_8mbtdxxxxx_file_63563df5df66488cb8e28bfff11e40eb_10285263_0_0"
},
"Score": 0.15737050771713257,
"Text": "Name: Wu Wang Sex: Male Age: 23"
}
]
},
"Message": "success",
"RequestId": "12A5F9C6-xxxx-5593-8955-86D52585EE27",
"Status": 200,
"Success": true
}Java
TagQueryExample.java
// The sample code is for reference only. Do not use it in a production environment.
import com.aliyun.bailian20231229.models.RetrieveRequest;
import com.aliyun.bailian20231229.models.RetrieveResponse;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class TagQueryExample {
/**
* descriptionSample request
{
"IndexId": "8mbtdxxxxx",
"WorkspaceId": "llm-4u5xpd1xdjxxxxxx",
"Query": "Provide some candidates",
"SearchFilters": "[{\"tags\":\"[\\\"University A\\\", \\\"Student Union President\\\"]\"}]"
}Sample response
{
"Code": "Success",
"Data": {
"Nodes": [
{
"Metadata": {
"file_path": "https://bailian-datahub-data-prod.oss-cn-beijing.aliyuncs.com/10285263/multimodal/docJson/Zhang_San_Resume_1746760910599.json?Expires=1747020348&OSSAccessKeyId=LTAI************&Signature=roY%2Falbh6smkLdPuA6wjnZRVMa4%3D",
"is_displayed_chunk_content": "true",
"_rc_v_score": 0.1422617520249937,
"image_url": [],
"nid": "ba8a14099f43308734538c29271cc7cd|b99e98835c3c6d8f6496df5a43de0ba5|aa3ed8fc4aae8bbb78872994b01e0fda",
"_q_score": 0.8935035934804278,
"source": "0",
"_score": 0.1736905574798584,
"title": "",
"doc_id": "file_e787926158704f95aad6bc967619f176_10285263",
"content": "Name: San Zhang Sex: Male Age: 23",
"_rc_score": 0,
"workspace_id": "llm-4u5xpd1xdjxxxxxx",
"hier_title": "",
"page_number": [
0
],
"doc_name": "San Zhang's Resume",
"pipeline_id": "8mbtdxxxxx",
"_id": "llm-4u5xpd1xdjxxxxxx_8mbtdxxxxx_file_e787926158704f95aad6bc967619f176_10285263_0_0"
},
"Score": 0.1736905574798584,
"Text": "Name: San Zhang Sex: Male Age: 23"
},
{
"Metadata": {
"file_path": "https://bailian-datahub-data-prod.oss-cn-beijing.aliyuncs.com/10285263/multimodal/docJson/Wang_Wu_Resume_1746760946844.json?Expires=1747020348&OSSAccessKeyId=LTAI************&Signature=gTGPTce5xUu9mtcMcmyMEeb5azk%3D",
"is_displayed_chunk_content": "true",
"_rc_v_score": 0.1592178845871759,
"image_url": [],
"nid": "ba8a14099f43308734538c29271cc7cd|d4a048b6799ce07e08430f018af091a0|fe90f8248ea64f70ea37c0df7afcfc12",
"_q_score": 1,
"source": "0",
"_score": 0.15737050771713257,
"title": "",
"doc_id": "file_63563df5df66488cb8e28bfff11e40eb_10285263",
"content": "Name: Wu Wang Sex: Male Age: 23",
"_rc_score": 0,
"workspace_id": "llm-4u5xpd1xdjxxxxxx",
"hier_title": "",
"page_number": [
0
],
"doc_name": "Wu Wang's Resume",
"pipeline_id": "8mbtdxxxxx",
"_id": "llm-4u5xpd1xdjxxxxxx_8mbtdxxxxx_file_63563df5df66488cb8e28bfff11e40eb_10285263_0_0"
},
"Score": 0.15737050771713257,
"Text": "Name: Wu Wang Sex: Male Age: 23"
}
]
},
"Message": "success",
"RequestId": "12A5F9C6-xxxx-5593-8955-86D52585EE27",
"Status": 200,
"Success": true
}Example: Use SearchFilters to query the talent knowledge base and return text segments from files that have both the University A and Sports Specialist Student tags (logical AND):
{
"searchFilters": [
{
"tags": "['University A']"
},
{
"tags": "['Sports Specialist Student']"
}
]
}Expand the following panels to view the sample code.
Python
TagQueryExample2.py
import json
import os
import sys
from typing import List
from alibabacloud_bailian20231229 import models as bailian_20231229_models
from alibabacloud_bailian20231229.client import Client as bailian20231229Client
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_tea_util.client import Client as UtilClient
class TagQueryExample2:
def __init__(self):
pass
@staticmethod
def create_client() -> bailian20231229Client:
"""
Initializes a client using an AccessKey pair.
@return: Client
@throws Exception
"""
# Leaking code that contains an AccessKey pair threatens the security of all resources in your account. The following sample code is for reference only.
# We recommend that you use a more secure method, such as Security Token Service (STS), to manage access credentials. For more information, see https://www.alibabacloud.com/help/zh/sdk/developer-reference/v2-manage-python-access-credentials.
config = open_api_models.Config(
# Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set.
access_key_id=os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'],
# Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set.
access_key_secret=os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
)
# For more information about endpoints, see https://www.alibabacloud.com/help/model-studio/api-bailian-2023-12-29-endpoint
config.endpoint = f'bailian.ap-southeast-1.aliyuncs.com'
return bailian20231229Client(config)
@staticmethod
def main(
args: List[str],
) -> None:
client = TagQueryExample.create_client()
# Create a retrieve_request object.
retrieve_request = bailian_20231229_models.RetrieveRequest()
# Required. You can enter the actual prompt.
retrieve_request.query = 'Provide some candidates'
# Required. Enter the actual knowledge base ID.
retrieve_request.index_id = 'Enter the actual knowledge base ID'
# Create two lists to store tags.
tag1 = ["University A"]
tag2 = ["Sports Specialist Student"]
retrieve_request.search_filters = [
{"tags": json.dumps(tag1)},
{"tags": json.dumps(tag2)}
]
try:
# Perform a retrieval. Enter the workspace ID and the retrieve_request object.
resp = client.retrieve('Enter the actual workspace ID', retrieve_request)
print(UtilClient.to_jsonstring(resp.body))
except Exception as error:
# This is for demonstration only. Handle exceptions with caution. Do not ignore exceptions in your project.
# Error message
print(error.message)
if __name__ == '__main__':
TagQueryExample2.main(sys.argv[1:]) Sample request
{
"IndexId": "8mbtdxxxxx",
"WorkspaceId": "llm-4u5xpd1xdjxxxxxx",
"Query": "Provide some candidates",
"SearchFilters": "[{\"tags\":\"[\\\"University A\\\"]\"},{\"tags\":\"[\\\"Sports Specialist Student\\\"]\"}]"
}Sample response
{
"Code": "Success",
"Data": {
"Nodes": [
{
"Metadata": {
"file_path": "https://bailian-datahub-data-prod.oss-cn-beijing.aliyuncs.com/10285263/multimodal/docJson/Zhang_San_Resume_1746760910599.json?Expires=1747020348&OSSAccessKeyId=LTAI************&Signature=roY%2Falbh6smkLdPuA6wjnZRVMa4%3D",
"is_displayed_chunk_content": "true",
"_rc_v_score": 0.1422617520249937,
"image_url": [],
"nid": "ba8a14099f43308734538c29271cc7cd|b99e98835c3c6d8f6496df5a43de0ba5|aa3ed8fc4aae8bbb78872994b01e0fda",
"_q_score": 1,
"source": "0",
"_score": 0.1736905574798584,
"title": "",
"doc_id": "file_e787926158704f95aad6bc967619f176_10285263",
"content": "Name: San Zhang Sex: Male Age: 23",
"_rc_score": 0,
"workspace_id": "llm-4u5xpd1xdjxxxxxx",
"hier_title": "",
"page_number": [
0
],
"doc_name": "San Zhang's Resume",
"pipeline_id": "8mbtdxxxxx",
"_id": "llm-4u5xpd1xdjxxxxxx_8mbtdxxxxx_file_e787926158704f95aad6bc967619f176_10285263_0_0"
},
"Score": 0.1736905574798584,
"Text": "Name: San Zhang Sex: Male Age: 23"
}
]
},
"Message": "success",
"RequestId": "1ED6CECE-xxxx-5B21-91DB-410E0219412A",
"Status": 200,
"Success": true
}
Java
TagQueryExample2.java
import com.aliyun.bailian20231229.models.RetrieveRequest;
import com.aliyun.bailian20231229.models.RetrieveResponse;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class TagQueryExample2 {
/**
* descriptionSample request
{
"IndexId": "8mbtdxxxxx",
"WorkspaceId": "llm-4u5xpd1xdjxxxxxx",
"Query": "Provide some candidates",
"SearchFilters": "[{\"tags\":\"[\\\"University A\\\"]\"},{\"tags\":\"[\\\"Sports Specialist Student\\\"]\"}]"
}Sample response
{
"Code": "Success",
"Data": {
"Nodes": [
{
"Metadata": {
"file_path": "https://bailian-datahub-data-prod.oss-cn-beijing.aliyuncs.com/10285263/multimodal/docJson/Zhang_San_Resume_1746760910599.json?Expires=1747020348&OSSAccessKeyId=LTAI************&Signature=roY%2Falbh6smkLdPuA6wjnZRVMa4%3D",
"is_displayed_chunk_content": "true",
"_rc_v_score": 0.1422617520249937,
"image_url": [],
"nid": "ba8a14099f43308734538c29271cc7cd|b99e98835c3c6d8f6496df5a43de0ba5|aa3ed8fc4aae8bbb78872994b01e0fda",
"_q_score": 1,
"source": "0",
"_score": 0.1736905574798584,
"title": "",
"doc_id": "file_e787926158704f95aad6bc967619f176_10285263",
"content": "Name: San Zhang Sex: Male Age: 23",
"_rc_score": 0,
"workspace_id": "llm-4u5xpd1xdjxxxxxx",
"hier_title": "",
"page_number": [
0
],
"doc_name": "San Zhang's Resume",
"pipeline_id": "8mbtdxxxxx",
"_id": "llm-4u5xpd1xdjxxxxxx_8mbtdxxxxx_file_e787926158704f95aad6bc967619f176_10285263_0_0"
},
"Score": 0.1736905574798584,
"Text": "Name: San Zhang Sex: Male Age: 23"
}
]
},
"Message": "success",
"RequestId": "1ED6CECE-xxxx-5B21-91DB-410E0219412A",
"Status": 200,
"Success": true
}
References
Knowledge base user guide | For more information, see Create and use a knowledge base. |
Retrieve a knowledge base | You can call the Retrieve API to retrieve from a knowledge base and return text segments. |
Call by a RAM user | Before a RAM user can call the Retrieve API, the user must obtain database permissions for Alibaba Cloud Model Studio. For more information, see Grant API permissions to a RAM user. |
Error codes
If a call fails and an error message is returned, see the Error center to resolve the issue.

