Knowledge base SearchFilters
The Retrieve API returns text segments from a knowledge base based on semantic similarity. When semantic search returns too many irrelevant results, use SearchFilters to apply metadata-based filtering on top of semantic results. This is effective for structured data such as data tables with well-defined fields.
Refers to the Retrieve API of a knowledge base.
Effect comparison
| Retrieve API request (without SearchFilters) | Retrieve API request (with SearchFilters) |
|---|---|
Retrieve request body: | Retrieve request body: |
Retrieve API response: Traditional semantic search returns some text segments that are not very relevant to the query (San Zhang). | Retrieve API response: By setting retrieval conditions (SearchFilters), text segments irrelevant to the query (San Zhang) are filtered out of the semantic search results. |
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) and further filters the text segments found through the user prompt. Subgroups in the array use AND logic; multiple retrieval fields in the same subgroup also use AND logic by default, which can be changed to OR by setting _operator in that subgroup. For how to use subgroups, see Subgroup query example.
{
"searchFilters": [
{
"Name": "San Zhang",
"Sex": "Male"
},
{
"Position": "Technician"
}
]
}
Choose the SearchFilters syntax based on your invocation method:
| Invocation method | Retrieval endpoint | Multiple OR conditions on the same field |
|---|---|---|
| OpenAPI Retrieve and its SDKs | POST https://bailian.cn-beijing.aliyuncs.com/{WorkspaceId}/index/retrieve | Nested _conditions are not supported; only flat maps are supported. |
| RAG API | POST https://{workspace_id}.cn-beijing.maas.aliyuncs.com/api/v1/indices/rag/index/retrieve | _operator and nested _conditions are supported. |
| Spring AI Alibaba DashScope SDK | /api/v1/indices/pipeline/{pipeline_id}/retrieve | _operator and nested _conditions are supported. |
Multi-field OR queries (OpenAPI Retrieve): In the same subgroup, place _operator alongside the retrieval fields and set it to OR (lowercase or is also supported) to match any field condition. If _operator is omitted or set to AND, all field conditions in that subgroup must be satisfied.
For example, the following filter matches chunks whose document name (doc_name) is "Long-context Qwen-Long" or whose chunk title (title) is "Returned results". Replace the fields and values with the fields and values that are actually searchable in your knowledge base.
{
"searchFilters": [
{
"_operator": "OR",
"doc_name": "Long-context Qwen-Long",
"title": "Returned results"
}
]
}
When using the Python client in the complete code example below, you can replace retrieve_request.search_filters with:
retrieve_request.search_filters = [
{
"_operator": "OR",
"doc_name": "Long-context Qwen-Long",
"title": "Returned results"
}
]
The SearchFilters of the OpenAPI SDK uses maps with string values and does not support nested _conditions. If you pass in a nested structure, the request may still return a success response, but the results are not filtered by the nested conditions and may not be filtered as expected. Field names in a flat map cannot be repeated, so this invocation method cannot express multiple independent conditions on the same field.
To add more conditions, place them in another subgroup in the array. For example, appending {"doc_name": "Long-context Qwen-Long"} after the preceding OR subgroup makes the overall condition "(document name is Long-context Qwen-Long OR chunk title is Returned results) AND document name is Long-context Qwen-Long". _operator changes only the relationship between fields in its own subgroup, not the AND relationship between subgroups in the array.
Same-field multi-condition OR queries (RAG API or Spring AI Alibaba): When you call the retrieval API through the JSON request body of the RAG API or through the Spring AI Alibaba DashScope SDK, you can place multiple conditions in the _conditions array and use _operator to specify the relationship between them. The full RAG API endpoint is:
POST https://{workspace_id}.cn-beijing.maas.aliyuncs.com/api/v1/indices/rag/index/retrieve
The Spring AI Alibaba DashScope SDK uses the following path:
/api/v1/indices/pipeline/{pipeline_id}/retrieve
SAA applications can also call the preceding RAG API URL directly through RestClient or WebClient, without going through the SDK's Pipeline retrieval path. For how to choose between the two methods and Java integration examples, see Retrieve a knowledge base through Spring AI Alibaba.
For example, the following filter matches records where "the department equals Corporate, or the department name contains Research, or the document type contains Policy". The _conditions array allows multiple objects to use the same field name, so exact and fuzzy queries can be combined. department and document_type are custom field names of the example knowledge base. Replace them with the field names in your actual schema:
{
"index_id": "your-index-id",
"query": "Find policy documents",
"search_filters": [
{
"_operator": "OR",
"_conditions": [
{ "department": "Corporate" },
{ "department": { "like": "%Research%" } },
{ "document_type": { "like": "%Policy%" } }
]
}
]
}
With Spring AI Alibaba 1.1.2.3, configure the same conditions in DashScopeDocumentRetrieverOptions from Retrieve a knowledge base through Spring AI Alibaba:
List<Map<String, Object>> searchFilters = List.of(Map.of(
"_operator", "OR",
"_conditions", List.of(
Map.of("department", "Corporate"),
Map.of("department", Map.of("like", "%Research%")),
Map.of("document_type", Map.of("like", "%Policy%"))
)
));
DashScopeDocumentRetrieverOptions options = DashScopeDocumentRetrieverOptions.builder()
.indexName("your-knowledge-base-name")
.searchFilters(searchFilters)
.build();
_operator controls only the condition relationship within its _conditions array. Different subgroups in search_filters still use AND logic.
Retrieval fields in a subgroup support single-value queries, multi-value queries, range queries, fuzzy queries, and tag queries.
-
Single-value queries: Field types support only numeric (long or double) and string. For how to use single-value queries, see Single-value query example.
-
Multi-value queries: Only arrays that consist purely of numeric values (long or double) or strings are supported. For how to use multi-value queries, see Multi-value query example.
-
Range queries: Support equality queries and interval queries. For how to use range queries, see Range query example.
- Equality queries: Support the
eq(equal to) andneq(not equal to) attributes. Field types support numeric (long or double) and string. A field cannot be configured with multiple values (case-insensitive). - Interval queries: Support the
gt(greater than),gte(greater than or equal to),lt(less than), andlte(less than or equal to) attributes. Field types support only numeric values (long, double).
- Equality queries: Support the
-
Fuzzy queries: Field types support only string. The
likeattribute is supported. For how to use fuzzy queries, see Fuzzy query example. -
Tag queries: Only document search and audio/video search knowledge bases are supported. For how to use tag queries, see Tag query example.
Prerequisites
-
RAM users (not required for the primary account) must obtain the AliyunBailianDataFullAccess policy and join a workspace before they can use Alibaba Cloud APIs to manage knowledge bases.
RAM users can manage knowledge bases only in the workspaces they have joined; the primary account can manage knowledge bases in all workspaces.
-
Install the Alibaba Cloud Bailian SDK and configure the environment.
-
Obtain an AccessKey and an AccessKey Secret and configure them as environment variables.
-
Prepare the employee information table Employee Information Table.xlsx (containing three records) for creating a knowledge base (used in the examples below). 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) and Age (double)
- Index settings: All fields are used for retrieval and model responses
After the configuration is complete, the Employee Sheet in the employee information knowledge base shows the Import Success status, and the table contains three sample employee records: San Zhang, Si Li, and Wu Wang.
-
Knowledge base configuration:
Complete code examples
Expand the panels below to view the complete Python and Java example code provided in this topic (for other languages, refer to the examples and implement your own).
Before you call the example code, you must obtain an AccessKey and an AccessKey Secret and configure them as environment variables.
Python
SearchFiltersFullExample.py
# The sample code is for reference only. Do not use it directly 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:
"""
Initialize an account client with an AccessKey pair.
@return: Client
@throws Exception
"""
# Project code leaks may disclose the AccessKey and threaten the security of all resources under the account. The following sample code is for reference only.
# We recommend the more secure STS method. For more authentication methods, see https://help.aliyun.com/document_detail/378659.html.
config = open_api_models.Config(
# Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set in the runtime environment.
access_key_id=os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'],
# Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set in the runtime environment.
access_key_secret=os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
)
# For endpoints, see https://api.aliyun.com/product/bailian
config.endpoint = f'bailian.cn-beijing.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 pass in the prompt that users actually enter.
retrieve_request.query = 'Employees in the company named San Zhang'
# Required. Pass in the actual knowledge base ID.
retrieve_request.index_id = 'Enter the actual knowledge base ID'
# Group 1 queries the Name attribute with the value San Zhang. Group 2 queries the Sex attribute with the value Female. You can replace them with the attributes and values to query.
retrieve_request.search_filters = [
{"Name": "San Zhang"},
{"Sex": "Female"}
]
# Perform a retrieval. Pass in 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 printing and display only. Handle exceptions with care and never ignore them directly in engineering projects.
# 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 pass in the prompt that users actually enter.
retrieve_request.query = 'Employees in the company named San Zhang'
# Required. Pass in the actual knowledge base ID.
retrieve_request.index_id = 'Enter the actual knowledge base ID'
# The single-value query uses the Name attribute with the value San Zhang. You can replace them with the attribute and value to query.
retrieve_request.search_filters = [
{"Name": "San Zhang"}
]
# Perform a retrieval. Pass in 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 printing and display only. Handle exceptions with care and never ignore them directly in engineering projects.
# 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 pass in the prompt that users actually enter.
retrieve_request.query = 'All employees in the company'
# Required. Pass in 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 multi-value query uses the Name attribute, corresponding to the names list above. The values are the multiple values "San Zhang" and "Si Li" specified above. You can replace them with the attributes and values to query.
retrieve_request.search_filters = [{"Name": json.dumps(names)}]
# Perform a retrieval. Pass in 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 printing and display only. Handle exceptions with care and never ignore them directly in engineering projects.
# 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 pass in the prompt that users actually enter.
retrieve_request.query = 'All employees in the company'
# Required. Pass in the actual knowledge base ID.
retrieve_request.index_id = 'Enter the actual knowledge base ID'
# The query uses the Age attribute with a range value. You can replace it with the attribute and value to query.
age_range = SearchFiltersFullExample.Range(20, 27)
retrieve_request.search_filters = [
{"Position": "Technician"}, # Group 1: Position filter condition
{"Age": json.dumps(age_range.to_dict())} # Group 2: Age range filter condition
]
# Perform a retrieval. Pass in 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 printing and display only. Handle exceptions with care and never ignore them directly in engineering projects.
# 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 pass in the prompt that users actually enter.
retrieve_request.query = 'Male employees in the company'
# Required. Pass in the actual knowledge base ID.
retrieve_request.index_id = 'Enter the actual knowledge base ID'
# The fuzzy query uses the Position attribute with the value Tech%ian, where % matches any characters (including zero characters). You can replace it with the actual value.
position = SearchFiltersFullExample.QueryObject('Tech%ian')
retrieve_request.search_filters = [
{"Name": "San Zhang"}, # Name filter condition. You can replace it with the attribute and value to query.
{"Position": json.dumps(position.to_dict())} # Position (fuzzy query) filter condition. You can replace it with the attribute and value to query.
]
# Perform a retrieval. Pass in 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 printing and display only. Handle exceptions with care and never ignore them directly in engineering projects.
# 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 pass in the prompt that users actually enter.
retrieve_request.query = 'Provide some candidates'
# Required. Pass in the actual knowledge base ID.
retrieve_request.index_id = 'Enter the actual knowledge base ID'
# Create a list to store tags. Multiple tags use OR logic, not AND logic.
tags = ["University A", "Student Union President"]
retrieve_request.search_filters = [
{"tags": json.dumps(tags)}
]
# Perform a retrieval. Pass in 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 printing and display only. Handle exceptions with care and never ignore them directly in engineering projects.
# 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 pass in the prompt that users actually enter.
retrieve_request.query = 'Provide some candidates'
# Required. Pass in 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. Pass in 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 printing and display only. Handle exceptions with care and never ignore them directly in engineering projects.
# 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 directly 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 {
/**
* <b>description</b> :
* <p>Initialize an account client with an AccessKey pair.</p>
*
* @return Client
* @throws Exception
*/
public static com.aliyun.bailian20231229.Client createClient() throws Exception {
// Project code leaks may disclose the AccessKey and threaten the security of all resources under the account. The following sample code is for reference only.
// We recommend the more secure STS method. For more authentication methods, see https://help.aliyun.com/document_detail/378657.html.
com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
// Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set in the runtime environment.
.setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
// Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set in the runtime environment.
.setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
// For endpoints, see https://api.aliyun.com/product/bailian
config.endpoint = "bailian.cn-beijing.aliyuncs.com";
return new com.aliyun.bailian20231229.Client(config);
}
public static void subgroupQuery() {
try {
com.aliyun.bailian20231229.Client client = createClient();
// Create a RetrieveRequest object.
RetrieveRequest request = new RetrieveRequest();
// Required. You can pass in the prompt that users actually enter.
request.setQuery("Employees in the company named San Zhang");
// Required. Pass in the actual knowledge base ID.
request.setIndexId("Enter the actual knowledge base ID");
Map<String, String> map1 = new HashMap<>();
// Group 1 queries the Name attribute with the value San Zhang. You can replace them with the attributes and values to query.
map1.put("Name", "San Zhang");
Map<String, String> map2 = new HashMap<>();
// Group 2 queries the Sex attribute with the value Female. You can replace them with the attributes and values to query.
map2.put("Sex", "Female");
List<Map<String, String>> searchFilters = new ArrayList<>();
searchFilters.add(map1);
searchFilters.add(map2);
request.setSearchFilters(searchFilters);
// Perform a retrieval. Pass in the workspace ID and the RetrieveRequest.
RetrieveResponse resp = client.retrieve("Enter the actual workspace ID", request);
System.out.println(new Gson().toJson(resp.getBody()));
} catch (Exception e) {
// Handle knowledge base retrieval failures.
// This is for printing and display only. Handle exceptions with care and never ignore them directly in engineering projects.
System.out.println(e.getMessage());
}
}
public static void singleQuery() {
try {
com.aliyun.bailian20231229.Client client = createClient();
// Create a RetrieveRequest object.
RetrieveRequest request = new RetrieveRequest();
// Required. You can pass in the prompt that users actually enter.
request.setQuery("Employees in the company named San Zhang");
// Required. Pass in the actual knowledge base ID.
request.setIndexId("Enter the actual knowledge base ID");
Map<String, String> map = new HashMap<>();
// The single-value query uses the Name attribute with the value San Zhang. You can replace them with the attribute and value to query.
map.put("Name", "San Zhang");
List<Map<String, String>> searchFilters = new ArrayList<>();
searchFilters.add(map);
request.setSearchFilters(searchFilters);
// Perform a retrieval. Pass in the workspace ID and the RetrieveRequest.
RetrieveResponse resp = client.retrieve("Enter the actual workspace ID", request);
System.out.println(new Gson().toJson(resp.getBody()));
} catch (Exception e) {
// Handle knowledge base retrieval failures.
// This is for printing and display only. Handle exceptions with care and never ignore them directly in engineering projects.
System.out.println(e.getMessage());
}
}
public static void multiQuery() {
try {
com.aliyun.bailian20231229.Client client = createClient();
// Create a RetrieveRequest object.
RetrieveRequest request = new RetrieveRequest();
// Required. You can pass in the prompt that users actually enter.
request.setQuery("All employees in the company");
// Required. Pass in the actual knowledge base ID.
request.setIndexId("Enter the actual knowledge base ID");
// Create a JsonArray to store multiple values.
JsonArray array = new JsonArray();
array.add("San Zhang");
array.add("Si Li");
Map<String, String> map = new HashMap<>();
// The multi-value query uses the Name attribute with the multiple values "San Zhang" and "Si Li" specified above. You can replace them with the attribute and values to query.
map.put("Name", array.toString());
List<Map<String, String>> searchFilters = new ArrayList<>();
searchFilters.add(map);
request.setSearchFilters(searchFilters);
// Perform a retrieval. Pass in the workspace ID and the RetrieveRequest.
RetrieveResponse resp = client.retrieve("Enter the actual workspace ID", request);
System.out.println(new Gson().toJson(resp.getBody()));
} catch (Exception e) {
// Handle knowledge base retrieval failures.
// This is for printing and display only. Handle exceptions with care and never ignore them directly in engineering projects.
System.out.println(e.getMessage());
}
}
public static void rangeQuery() {
try {
com.aliyun.bailian20231229.Client client = createClient();
// Create a RetrieveRequest object.
RetrieveRequest request = new RetrieveRequest();
// Required. You can pass in the prompt that users actually enter.
request.setQuery("All employees in the company");
// Required. Pass in the actual knowledge base ID.
request.setIndexId("Enter the actual knowledge base ID");
Map<String, String> map1 = new HashMap<>();
// Group 1 queries the Sex attribute with the value Male. You can replace them with the attributes and values to query.
map1.put("Sex", "Male");
// Group 2 queries the Age attribute with a range value. You can replace them with the attributes and values to query.
Map<String, String> map2 = new HashMap<>();
Range range = new Range(20, 27);
map2.put("Age", new Gson().toJson(range));
List<Map<String, String>> searchFilters = new ArrayList<>();
searchFilters.add(map1);
searchFilters.add(map2);
request.setSearchFilters(searchFilters);
// Perform a retrieval. Pass in the workspace ID and the RetrieveRequest.
RetrieveResponse resp = client.retrieve("Enter the actual workspace ID", request);
System.out.println(new Gson().toJson(resp.getBody()));
} catch (Exception e) {
// Handle knowledge base retrieval failures.
// This is for printing and display only. Handle exceptions with care and never ignore them directly in engineering projects.
System.out.println(e.getMessage());
}
}
public static void wildcardQuery() {
try {
com.aliyun.bailian20231229.Client client = createClient();
// Create a RetrieveRequest object.
RetrieveRequest request = new RetrieveRequest();
// Required. You can pass in the prompt that users actually enter.
request.setQuery("Male employees in the company");
// Required. Pass in the actual knowledge base ID.
request.setIndexId("Enter the actual knowledge base ID");
// Group 1 queries the Name attribute with the value San Zhang. You can replace them with the attributes and values to query.
Map<String, String> map1 = new HashMap<>();
map1.put("Name", "San Zhang");
// Group 2 queries the Position attribute with the value Tech%ian, where % matches any characters (including zero characters). You can replace them with the attributes and values to query.
Map<String, String> map2 = new HashMap<>();
QueryObject queryObject = new QueryObject("Tech%ian");
map2.put("Position", new Gson().toJson(queryObject));
List<Map<String, String>> searchFilters = new ArrayList<>();
searchFilters.add(map1);
searchFilters.add(map2);
request.setSearchFilters(searchFilters);
// Perform a retrieval. Pass in the workspace ID and the RetrieveRequest.
RetrieveResponse resp = client.retrieve("Enter the actual workspace ID", request);
System.out.println(new Gson().toJson(resp.getBody()));
} catch (Exception e) {
// Handle knowledge base retrieval failures.
// This is for printing and display only. Handle exceptions with care and never ignore them directly in engineering projects.
System.out.println(e.getMessage());
}
}
public static void tagQuery() {
try {
com.aliyun.bailian20231229.Client client = createClient();
// Create a RetrieveRequest object.
RetrieveRequest request = new RetrieveRequest();
// Required. You can pass in the prompt that users actually enter.
request.setQuery("Provide some candidates");
// Required. Pass in the actual knowledge base ID.
request.setIndexId("Enter the actual knowledge base ID");
// Create a JsonArray to store tags. Multiple tags use OR logic, not AND logic.
JsonArray array = new JsonArray();
array.add("University A");
array.add("Student Union President");
Map<String, String> map = new HashMap<>();
map.put("tags", array.toString());
List<Map<String, String>> searchFilters = new ArrayList<>();
searchFilters.add(map);
request.setSearchFilters(searchFilters);
// Perform a retrieval. Pass in the workspace ID and the RetrieveRequest.
RetrieveResponse resp = client.retrieve("Enter the actual workspace ID", request);
System.out.println(new Gson().toJson(resp.getBody()));
} catch (Exception e) {
// Handle knowledge base retrieval failures.
// This is for printing and display only. Handle exceptions with care and never ignore them directly in engineering projects.
System.out.println(e.getMessage());
}
}
public static void tagQuery2() {
try {
com.aliyun.bailian20231229.Client client = createClient();
// Create a RetrieveRequest object.
RetrieveRequest request = new RetrieveRequest();
// Required. You can pass in the prompt that users actually enter.
request.setQuery("Provide some candidates");
// Required. Pass in the actual knowledge base ID.
request.setIndexId("Enter the actual knowledge base ID");
// Create a JsonArray to store tags.
JsonArray tag1 = new JsonArray();
tag1.add("University A");
JsonArray tag2 = new JsonArray();
tag2.add("Sports Specialist Student");
Map<String, String> map1 = new HashMap<>();
map1.put("tags", tag1.toString());
Map<String, String> map2 = new HashMap<>();
map2.put("tags", tag2.toString());
List<Map<String, String>> searchFilters = new ArrayList<>();
searchFilters.add(map1);
searchFilters.add(map2);
request.setSearchFilters(searchFilters);
// Perform a retrieval. Pass in the workspace ID and the RetrieveRequest.
RetrieveResponse resp = client.retrieve("Enter the actual workspace ID", request);
System.out.println(new Gson().toJson(resp.getBody()));
} catch (Exception e) {
// Handle knowledge base retrieval failures.
// This is for printing and display only. Handle exceptions with care and never ignore them directly in engineering projects.
System.out.println(e.getMessage());
}
}
public static void main(String[] args) {
subgroupQuery();
singleQuery();
multiQuery();
rangeQuery();
wildcardQuery();
tagQuery();
tagQuery2();
}
static class Range {
double gte;
double lte;
public Range(double gte, double lte) {
this.gte = gte;
this.lte = lte;
}
}
static class QueryObject {
String like;
public QueryObject(String prefix) {
this.like = prefix;
}
public String getLike() {
return like;
}
public void setLike(String like) {
this.like = like;
}
}
}
Quick start
The following describes how to use SearchFilters for queries.
Subgroup query example
Subgroups are used to filter the recall results of a knowledge base so that only text segments that meet specific conditions are returned. You can add multiple subgroups (conditions) to SearchFilters. Subgroups use AND logic by default, which cannot be changed.
Example: Search the employee information knowledge base and filter out records where Name is San Zhang and Sex is Female (no such record exists in this knowledge base).
{
"searchFilters": [
{
"Name": "San Zhang"
},
{
"Sex": "Female"
}
]
}
Expand the panels below to view the sample code.
Python
SubGroupQueryExample.py
# The sample code is for reference only. Do not use it directly 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:
"""
Initialize an account client with an AccessKey pair.
@return: Client
@throws Exception
"""
# Project code leaks may disclose the AccessKey and threaten the security of all resources under the account. The following sample code is for reference only.
# We recommend the more secure STS method. For more authentication methods, see https://help.aliyun.com/document_detail/378659.html.
config = open_api_models.Config(
# Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set in the runtime environment.
access_key_id=os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'],
# Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set in the runtime environment.
access_key_secret=os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
)
# For endpoints, see https://api.aliyun.com/product/bailian
config.endpoint = f'bailian.cn-beijing.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 pass in the prompt that users actually enter.
retrieve_request.query = 'Employees in the company named San Zhang'
# Required. Pass in the actual knowledge base ID.
retrieve_request.index_id = 'Enter the actual knowledge base ID'
# Group 1 queries the Name attribute with the value San Zhang. Group 2 queries the Sex attribute with the value Female. You can replace them with the attributes and values to query.
retrieve_request.search_filters = [
{"Name": "San Zhang"},
{"Sex": "Female"}
]
# Perform a retrieval. Pass in 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 printing and display only. Handle exceptions with care and never ignore them directly in engineering projects.
# 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 directly 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 {
/**
* <b>description</b> :
* <p>Initialize an account client with an AccessKey pair.</p>
* @return Client
*
* @throws Exception
*/
public static com.aliyun.bailian20231229.Client createClient() throws Exception {
// Project code leaks may disclose the AccessKey and threaten the security of all resources under the account. The following sample code is for reference only.
// We recommend the more secure STS method. For more authentication methods, see https://help.aliyun.com/document_detail/378657.html.
com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
// Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set in the runtime environment.
.setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
// Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set in the runtime environment.
.setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
// For endpoints, see https://api.aliyun.com/product/bailian
config.endpoint = "bailian.cn-beijing.aliyuncs.com";
return new com.aliyun.bailian20231229.Client(config);
}
public static void main(String[] args) {
try {
com.aliyun.bailian20231229.Client client = createClient();
// Create a RetrieveRequest object.
RetrieveRequest request = new RetrieveRequest();
// Required. You can pass in the prompt that users actually enter.
request.setQuery("Employees in the company named San Zhang");
// Required. Pass in the actual knowledge base ID.
request.setIndexId("Enter the actual knowledge base ID");
Map<String, String> map1 = new HashMap<>();
// Group 1 queries the Name attribute with the value San Zhang. You can replace them with the attributes and values to query.
map1.put("Name","San Zhang");
Map<String, String> map2 = new HashMap<>();
// Group 2 queries the Sex attribute with the value Female. You can replace them with the attributes and values to query.
map2.put("Sex","Female");
List<Map<String, String>> searchFilters = new ArrayList<>();
searchFilters.add(map1);
searchFilters.add(map2);
request.setSearchFilters(searchFilters);
// Perform a retrieval. Pass in the workspace ID and the RetrieveRequest.
RetrieveResponse resp = client.retrieve("Enter the actual workspace ID", request);
System.out.println(new Gson().toJson(resp.getBody()));
} catch (Exception e) {
// Handle knowledge base retrieval failures.
// This is for printing and display only. Handle exceptions with care and never ignore them directly in engineering projects.
System.out.println(e.getMessage());
}
}
}
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
}
Single-value query example
In a single-value query, you need to pass a unique value for the retrieval field.
Example: Search the employee information knowledge base and filter out records where Name is San Zhang.
{
"searchFilters": [
{
"Name": "San Zhang"
}
]
}
Expand the panels below to view the sample code.
Python
SingleQueryExample.py
# The sample code is for reference only. Do not use it directly 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:
"""
Initialize an account client with an AccessKey pair.
@return: Client
@throws Exception
"""
# Project code leaks may disclose the AccessKey and threaten the security of all resources under the account. The following sample code is for reference only.
# We recommend the more secure STS method. For more authentication methods, see https://help.aliyun.com/document_detail/378659.html.
config = open_api_models.Config(
# Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set in the runtime environment.
access_key_id=os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'],
# Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set in the runtime environment.
access_key_secret=os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
)
# For endpoints, see https://api.aliyun.com/product/bailian
config.endpoint = f'bailian.cn-beijing.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 pass in the prompt that users actually enter.
retrieve_request.query = 'Employees in the company named San Zhang'
# Required. Pass in the actual knowledge base ID.
retrieve_request.index_id = 'Enter the actual knowledge base ID'
# The single-value query uses the Name attribute with the value San Zhang. You can replace them with the attribute and value to query.
retrieve_request.search_filters = [
{"Name": "San Zhang"}
]
try:
# Perform a retrieval. Pass in 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 printing and display only. Handle exceptions with care and never ignore them directly in engineering projects.
# 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": "Technician"
},
"score": 0.4556944966316223,
"text": "Name:San Zhang Age:25 Position:Technician 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 directly 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 {
/**
* <b>description</b> :
* <p>Initialize an account client with an AccessKey pair.</p>
* @return Client
*
* @throws Exception
*/
public static com.aliyun.bailian20231229.Client createClient() throws Exception {
// Project code leaks may disclose the AccessKey and threaten the security of all resources under the account. The following sample code is for reference only.
// We recommend the more secure STS method. For more authentication methods, see https://help.aliyun.com/document_detail/378657.html.
com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
// Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set in the runtime environment.
.setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
// Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set in the runtime environment.
.setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
// For endpoints, see https://api.aliyun.com/product/bailian
config.endpoint = "bailian.cn-beijing.aliyuncs.com";
return new com.aliyun.bailian20231229.Client(config);
}
public static void main(String[] args) {
try {
com.aliyun.bailian20231229.Client client = createClient();
// Create a RetrieveRequest object.
RetrieveRequest request = new RetrieveRequest();
// Required. You can pass in the prompt that users actually enter.
request.setQuery("Employees in the company named San Zhang");
// Required. Pass in the actual knowledge base ID.
request.setIndexId("Enter the actual knowledge base ID");
Map<String, String> map = new HashMap<>();
// The single-value query uses the Name attribute with the value San Zhang. You can replace them with the attribute and value to query.
map.put("Name","San Zhang");
List<Map<String, String>> searchFilters = new ArrayList<>();
searchFilters.add(map);
request.setSearchFilters(searchFilters);
// Perform a retrieval. Pass in the workspace ID and the RetrieveRequest.
RetrieveResponse resp = client.retrieve("Enter the actual workspace ID", request);
System.out.println(new Gson().toJson(resp.getBody()));
} catch (Exception e) {
// Handle knowledge base retrieval failures.
// This is for printing and display only. Handle exceptions with care and never ignore them directly in engineering projects.
System.out.println(e.getMessage());
}
}
}
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_xxxx75507aab4bd9a24c18d098b2e8ac_10285263_1",
"Age": "25",
"Position": "Technician"
},
"score": 0.4556944966316223,
"text": "Name:San Zhang Age:25 Position:Technician Sex:Male"
}
]
},
"message": "success",
"requestId": "2FA4113E-xxxx-59C1-BDB2-5B930D8C9B1C",
"status": "200",
"success": true
}
Multi-value query example
Multi-value queries allow you to pass multiple values for a retrieval field, similar to the IN operator in SQL.
Example: Search the employee information knowledge base and filter out records where Name is San Zhang or Si Li.
{
"searchFilters": [
{
"Name": ["San Zhang","Si Li"]
}
]
}
Expand the panels below to view the sample code.
Python
MultiQueryExample.py
# The sample code is for reference only. Do not use it directly 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:
"""
Initialize an account client with an AccessKey pair.
@return: Client
@throws Exception
"""
# Project code leaks may disclose the AccessKey and threaten the security of all resources under the account. The following sample code is for reference only.
# We recommend the more secure STS method. For more authentication methods, see https://help.aliyun.com/document_detail/378659.html.
config = open_api_models.Config(
# Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set in the runtime environment.
access_key_id=os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'],
# Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set in the runtime environment.
access_key_secret=os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
)
# For endpoints, see https://api.aliyun.com/product/bailian
config.endpoint = f'bailian.cn-beijing.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 pass in the prompt that users actually enter.
retrieve_request.query = 'All employees in the company'
# Required. Pass in 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 multi-value query uses the Name attribute, corresponding to the names list above. The values are the multiple values "San Zhang" and "Si Li" specified above. You can replace them with the attributes and values to query.
retrieve_request.search_filters = [{"Name": json.dumps(names)}]
# Perform a retrieval. Pass in 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 printing and display only. Handle exceptions with care and never ignore them directly in engineering projects.
# 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": "Technician"
},
"score": 0.3322954773902893,
"text": "Name:San Zhang Age:25.0 Position:Technician 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 directly 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 {
/**
* <b>description</b> :
* <p>Initialize an account client with an AccessKey pair.</p>
* @return Client
*
* @throws Exception
*/
public static com.aliyun.bailian20231229.Client createClient() throws Exception {
// Project code leaks may disclose the AccessKey and threaten the security of all resources under the account. The following sample code is for reference only.
// We recommend the more secure STS method. For more authentication methods, see https://help.aliyun.com/document_detail/378657.html.
com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
// Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set in the runtime environment.
.setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
// Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set in the runtime environment.
.setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
// For endpoints, see https://api.aliyun.com/product/bailian
config.endpoint = "bailian.cn-beijing.aliyuncs.com";
return new com.aliyun.bailian20231229.Client(config);
}
public static void main(String[] args) {
try {
com.aliyun.bailian20231229.Client client = createClient();
// Create a RetrieveRequest object.
RetrieveRequest request = new RetrieveRequest();
// Required. You can pass in the prompt that users actually enter.
request.setQuery("All employees in the company");
// Required. Pass in the actual knowledge base ID.
request.setIndexId("Enter the actual knowledge base ID");
// Create a JsonArray to store multiple values.
JsonArray array = new JsonArray();
array.add("San Zhang");
array.add("Si Li");
Map<String, String> map = new HashMap<>();
// The multi-value query uses the Name attribute with the multiple values "San Zhang" and "Si Li" specified above. You can replace them with the attribute and values to query.
map.put("Name", array.toString());
List<Map<String, String>> searchFilters = new ArrayList<>();
searchFilters.add(map);
request.setSearchFilters(searchFilters);
// Perform a retrieval. Pass in the workspace ID and the RetrieveRequest.
RetrieveResponse resp = client.retrieve("Enter the actual workspace ID", request);
System.out.println(new Gson().toJson(resp.getBody()));
} catch (Exception e) {
// Handle knowledge base retrieval failures.
// This is for printing and display only. Handle exceptions with care and never ignore them directly in engineering projects.
System.out.println(e.getMessage());
}
}
}
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": "Technician"
},
"score": 0.3322954773902893,
"text": "Name:San Zhang Age:25.0 Position:Technician 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 example
Through range queries, you can find all records whose retrieval field (such as Age) values meet the conditions within a specified range.
Example: Search the employee information knowledge base and filter out records where Position is Technician (single-value query) and Age is between 20 and 25 (range query).
{
"searchFilters": [
{
"Position": "Technician"
},
{
"Age": {
"gte": 20,
"lte": 25
}
}
]
}
Expand the panels below to view the sample code.
Python
RangeQueryExample.py
# The sample code is for reference only. Do not use it directly 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:
"""
Initialize an account client with an AccessKey pair.
@return: Client
@throws Exception
"""
# Project code leaks may disclose the AccessKey and threaten the security of all resources under the account. The following sample code is for reference only.
# We recommend the more secure STS method. For more authentication methods, see https://help.aliyun.com/document_detail/378659.html.
config = open_api_models.Config(
# Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set in the runtime environment.
access_key_id=os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'],
# Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set in the runtime environment.
access_key_secret=os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
)
# For endpoints, see https://api.aliyun.com/product/bailian
config.endpoint = f'bailian.cn-beijing.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 pass in the prompt that users actually enter.
retrieve_request.query = 'All employees in the company'
# Required. Pass in the actual knowledge base ID.
retrieve_request.index_id = 'Enter the actual knowledge base ID'
# The query uses the Age attribute with a range value. You can replace it with the attribute and value to query.
age_range = RangeQueryExample.Range(20, 27)
retrieve_request.search_filters = [
{"Position": "Technician"}, # Group 1: Position filter condition
{"Age": json.dumps(age_range.to_dict())} # Group 2: Age range filter condition
]
# Perform a retrieval. Pass in 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 printing and display only. Handle exceptions with care and never ignore them directly in engineering projects.
# 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": "Technician"
},
"score": 0.3322954773902893,
"text": "Name:San Zhang Age:25.0 Position:Technician 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 directly 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 {
/**
* <b>description</b> :
* <p>Initialize an account client with an AccessKey pair.</p>
* @return Client
*
* @throws Exception
*/
public static com.aliyun.bailian20231229.Client createClient() throws Exception {
// Project code leaks may disclose the AccessKey and threaten the security of all resources under the account. The following sample code is for reference only.
// We recommend the more secure STS method. For more authentication methods, see https://help.aliyun.com/document_detail/378657.html.
com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
// Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set in the runtime environment.
.setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
// Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set in the runtime environment.
.setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
// For endpoints, see https://api.aliyun.com/product/bailian
config.endpoint = "bailian.cn-beijing.aliyuncs.com";
return new com.aliyun.bailian20231229.Client(config);
}
public static void main(String[] args) {
try {
com.aliyun.bailian20231229.Client client = createClient();
// Create a RetrieveRequest object.
RetrieveRequest request = new RetrieveRequest();
// Required. You can pass in the prompt that users actually enter.
request.setQuery("All employees in the company");
// Required. Pass in the actual knowledge base ID.
request.setIndexId("Enter the actual knowledge base ID");
Map<String, String> map1 = new HashMap<>();
// Group 1 queries the Sex attribute with the value Male. You can replace them with the attributes and values to query.
map1.put("Sex", "Male");
// Group 2 queries the Age attribute with a range value. You can replace them with the attributes and values to query.
Map<String, String> map2 = new HashMap<>();
Range range = new Range(20, 27);
map2.put("Age", new Gson().toJson(range));
List<Map<String, String>> searchFilters = new ArrayList<>();
searchFilters.add(map1);
searchFilters.add(map2);
request.setSearchFilters(searchFilters);
// Perform a retrieval. Pass in the workspace ID and the RetrieveRequest.
RetrieveResponse resp = client.retrieve("Enter the actual workspace ID", request);
System.out.println(new Gson().toJson(resp.getBody()));
} catch (Exception e) {
// Handle knowledge base retrieval failures.
// This is for printing and display only. Handle exceptions with care and never ignore them directly in engineering projects.
System.out.println(e.getMessage());
}
}
static class Range {
double gte;
double lte;
public Range(double gte, double lte) {
this.gte = gte;
this.lte = lte;
}
}
}
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": "Technician"
},
"score": 0.3322954773902893,
"text": "Name:San Zhang Age:25.0 Position:Technician Sex:Male"
}
]
},
"message": "success",
"requestId": "AE0B5ABC-xxxx-54A1-9ED4-91865B859DF6",
"status": "200",
"success": true
}
Fuzzy query example
Fuzzy queries find records containing specific character sequences by specifying wildcards, similar to the LIKE operator in SQL.
SearchFilters fuzzy queries support the following wildcards (consistent with SQL syntax):
Wildcard | Description |
|---|---|
% | Substitutes zero or more characters. |
_ | Substitutes one character. |
Example: Search the employee information knowledge base and filter out records where Name is San Zhang and Position contains the two character sequences Tech and ian (which can be Technician, Technical Personnel, and so on).
{
"searchFilters": [
{
"Name": "San Zhang"
},
{
"Position": {
"like": "Tech%ian"
}
}
]
}
Expand the panels below to view the sample code.
Python
WildcardQueryExample.py
# The sample code is for reference only. Do not use it directly 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:
"""
Initialize an account client with an AccessKey pair.
@return: Client
@throws Exception
"""
# Project code leaks may disclose the AccessKey and threaten the security of all resources under the account. The following sample code is for reference only.
# We recommend the more secure STS method. For more authentication methods, see https://help.aliyun.com/document_detail/378659.html.
config = open_api_models.Config(
# Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set in the runtime environment.
access_key_id=os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'],
# Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set in the runtime environment.
access_key_secret=os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
)
# For endpoints, see https://api.aliyun.com/product/bailian
config.endpoint = f'bailian.cn-beijing.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 pass in the prompt that users actually enter.
retrieve_request.query = 'Male employees in the company'
# Required. Pass in the actual knowledge base ID.
retrieve_request.index_id = 'Enter the actual knowledge base ID'
# The fuzzy query uses the Position attribute with the value Tech%ian, where % matches any characters (including zero characters). You can replace it with the actual value.
position = WildcardQueryExample.QueryObject('Tech%ian')
retrieve_request.search_filters = [
{"Name": "San Zhang"}, # Name filter condition. You can replace it with the attribute and value to query.
{"Position": json.dumps(position.to_dict())} # Position (fuzzy query) filter condition. You can replace it with the attribute and value to query.
]
# Perform a retrieval. Pass in 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 printing and display only. Handle exceptions with care and never ignore them directly in engineering projects.
# 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\":\"Tech%ian\"}"
}
]
}
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": "Technician"
},
"score": 0.46098726987838745,
"text": "Name:San Zhang Age:25.0 Position:Technician 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 directly 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 {
/**
* <b>description</b> :
* <p>Initialize an account client with an AccessKey pair.</p>
*
* @return Client
* @throws Exception
*/
public static com.aliyun.bailian20231229.Client createClient() throws Exception {
// Project code leaks may disclose the AccessKey and threaten the security of all resources under the account. The following sample code is for reference only.
// We recommend the more secure STS method. For more authentication methods, see https://help.aliyun.com/document_detail/378657.html.
com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
// Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set in the runtime environment.
.setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
// Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set in the runtime environment.
.setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
// For endpoints, see https://api.aliyun.com/product/bailian
config.endpoint = "bailian.cn-beijing.aliyuncs.com";
return new com.aliyun.bailian20231229.Client(config);
}
public static void main(String[] args_) {
try {
com.aliyun.bailian20231229.Client client = createClient();
// Create a RetrieveRequest object.
RetrieveRequest request = new RetrieveRequest();
// Required. You can pass in the prompt that users actually enter.
request.setQuery("Male employees in the company");
// Required. Pass in the actual knowledge base ID.
request.setIndexId("Enter the actual knowledge base ID");
// Group 1 queries the Name attribute with the value San Zhang. You can replace them with the attributes and values to query.
Map<String, String> map1 = new HashMap<>();
map1.put("Name", "San Zhang");
// Group 2 queries the Position attribute with the value Tech%ian, where % matches any characters (including zero characters). You can replace them with the attributes and values to query.
Map<String, String> map2 = new HashMap<>();
QueryObject queryObject = new QueryObject("Tech%ian");
map2.put("Position", new Gson().toJson(queryObject));
List<Map<String, String>> searchFilters = new ArrayList<>();
searchFilters.add(map1);
searchFilters.add(map2);
request.setSearchFilters(searchFilters);
// Perform a retrieval. Pass in the workspace ID and the RetrieveRequest.
RetrieveResponse resp = client.retrieve("Enter the actual workspace ID", request);
System.out.println(new Gson().toJson(resp.getBody()));
} catch (Exception e) {
// Handle knowledge base retrieval failures.
// This is for printing and display only. Handle exceptions with care and never ignore them directly in engineering projects.
System.out.println(e.getMessage());
}
}
static class QueryObject {
String like;
public QueryObject(String prefix) {
this.like = prefix;
}
public String getLike() {
return like;
}
public void setLike(String like) {
this.like = like;
}
}
}
Sample request
{
"indexId": "27ubwxxxxx",
"WorkspaceId":"llm-4u5xpd1xdjxxxxxx",
"query": "Male employees in the company",
"searchFilters": [
{
"Name": "San Zhang"
},
{
"Position": "{\"like\":\"Tech%ian\"}"
}
]
}
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": "Technician"
},
"score": 0.46098726987838745,
"text": "Name:San Zhang Age:25.0 Position:Technician Sex:Male"
}
]
},
"message": "success",
"requestId": "FA759FEC-xxxx-50B7-A64D-BE49A7DF56B8",
"status": "200",
"success": true
}
Tag query example
When searching document search or audio/video search knowledge bases, you can use tags to filter files and improve retrieval efficiency and accuracy.
Example: Create a document search knowledge base that contains information about San Zhang, Si Li, and Wu Wang.
The preceding files are tagged as follows:
File | Tags |
|---|---|
San Zhang's Resume |
|
Si Li's Resume |
|
Wu Wang's Resume |
|
For example, use SearchFilters to query the talent knowledge base and return text segments from files tagged University A or Student Union President:
Multiple tags use OR logic, not AND logic. You can implement AND logic through subgroup queries.
{
"searchFilters": [
{
"tags": ["University A","Student Union President"]
}
]
}
Expand the panels below to view the sample code.
Python
TagQueryExample.py
# The sample code is for reference only. Do not use it directly 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:
"""
Initialize an account client with an AccessKey pair.
@return: Client
@throws Exception
"""
# Project code leaks may disclose the AccessKey and threaten the security of all resources under the account. The following sample code is for reference only.
# We recommend the more secure STS method. For more authentication methods, see https://help.aliyun.com/document_detail/378659.html.
config = open_api_models.Config(
# Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set in the runtime environment.
access_key_id=os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'],
# Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set in the runtime environment.
access_key_secret=os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
)
# For endpoints, see https://api.aliyun.com/product/bailian
config.endpoint = f'bailian.cn-beijing.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 pass in the prompt that users actually enter.
retrieve_request.query = 'Provide some candidates'
# Required. Pass in the actual knowledge base ID.
retrieve_request.index_id = 'Enter the actual knowledge base ID'
# Create a list to store tags. Multiple tags use OR logic, not AND logic.
tags = ["University A", "Student Union President"]
retrieve_request.search_filters = [
{"tags": json.dumps(tags)}
]
try:
# Perform a retrieval. Pass in 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 printing and display only. Handle exceptions with care and never ignore them directly in engineering projects.
# 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=YOUR_ACCESS_KEY_ID&Signature=YOUR_SIGNATURE",
"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=YOUR_ACCESS_KEY_ID&Signature=YOUR_SIGNATURE",
"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 directly 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 {
/**
* <b>description</b> :
* <p>Initialize an account client with an AccessKey pair.</p>
*
* @return Client
* @throws Exception
*/
public static com.aliyun.bailian20231229.Client createClient() throws Exception {
// Project code leaks may disclose the AccessKey and threaten the security of all resources under the account. The following sample code is for reference only.
// We recommend the more secure STS method. For more authentication methods, see https://help.aliyun.com/document_detail/378657.html.
com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
// Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set in the runtime environment.
.setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
// Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set in the runtime environment.
.setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
// For endpoints, see https://api.aliyun.com/product/bailian
config.endpoint = "bailian.cn-beijing.aliyuncs.com";
return new com.aliyun.bailian20231229.Client(config);
}
public static void main(String[] args) {
try {
com.aliyun.bailian20231229.Client client = createClient();
// Create a RetrieveRequest object.
RetrieveRequest request = new RetrieveRequest();
// Required. You can pass in the prompt that users actually enter.
request.setQuery("Provide some candidates");
// Required. Pass in the actual knowledge base ID.
request.setIndexId("Enter the actual knowledge base ID");
// Create a JsonArray to store tags. Multiple tags use OR logic, not AND logic.
JsonArray array = new JsonArray();
array.add("University A");
array.add("Student Union President");
Map<String, String> map = new HashMap<>();
map.put("tags", array.toString());
List<Map<String, String>> searchFilters = new ArrayList<>();
searchFilters.add(map);
request.setSearchFilters(searchFilters);
// Perform a retrieval. Pass in the workspace ID and the RetrieveRequest.
RetrieveResponse resp = client.retrieve("Enter the actual workspace ID", request);
System.out.println(new Gson().toJson(resp.getBody()));
} catch (Exception e) {
// Handle knowledge base retrieval failures.
// This is for printing and display only. Handle exceptions with care and never ignore them directly in engineering projects.
System.out.println(e.getMessage());
}
}
}
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=YOUR_ACCESS_KEY_ID&Signature=YOUR_SIGNATURE",
"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=YOUR_ACCESS_KEY_ID&Signature=YOUR_SIGNATURE",
"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 tagged University A and Sports Specialist Student (AND logic):
{
"searchFilters": [
{
"tags": ["University A"]
},
{
"tags": ["Sports Specialist Student"]
}
]
}
Expand the panels below 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:
"""
Initialize an account client with an AccessKey pair.
@return: Client
@throws Exception
"""
# Project code leaks may disclose the AccessKey and threaten the security of all resources under the account. The following sample code is for reference only.
# We recommend the more secure STS method. For more authentication methods, see https://help.aliyun.com/document_detail/378659.html.
config = open_api_models.Config(
# Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set in the runtime environment.
access_key_id=os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'],
# Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set in the runtime environment.
access_key_secret=os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
)
# For endpoints, see https://api.aliyun.com/product/bailian
config.endpoint = f'bailian.cn-beijing.aliyuncs.com'
return bailian20231229Client(config)
@staticmethod
def main(
args: List[str],
) -> None:
client = TagQueryExample2.create_client()
# Create a retrieve_request object.
retrieve_request = bailian_20231229_models.RetrieveRequest()
# Required. You can pass in the prompt that users actually enter.
retrieve_request.query = 'Provide some candidates'
# Required. Pass in 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. Pass in 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 printing and display only. Handle exceptions with care and never ignore them directly in engineering projects.
# 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=YOUR_ACCESS_KEY_ID&Signature=YOUR_SIGNATURE",
"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 {
/**
* <b>description</b> :
* <p>Initialize an account client with an AccessKey pair.</p>
*
* @return Client
* @throws Exception
*/
public static com.aliyun.bailian20231229.Client createClient() throws Exception {
// Project code leaks may disclose the AccessKey and threaten the security of all resources under the account. The following sample code is for reference only.
// We recommend the more secure STS method. For more authentication methods, see https://help.aliyun.com/document_detail/378657.html.
com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
// Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set in the runtime environment.
.setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
// Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set in the runtime environment.
.setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
// For endpoints, see https://api.aliyun.com/product/bailian
config.endpoint = "bailian.cn-beijing.aliyuncs.com";
return new com.aliyun.bailian20231229.Client(config);
}
public static void main(String[] args) {
try {
com.aliyun.bailian20231229.Client client = createClient();
// Create a RetrieveRequest object.
RetrieveRequest request = new RetrieveRequest();
// Required. You can pass in the prompt that users actually enter.
request.setQuery("Provide some candidates");
// Required. Pass in the actual knowledge base ID.
request.setIndexId("Enter the actual knowledge base ID");
// Create a JsonArray to store tags.
JsonArray tag1 = new JsonArray();
tag1.add("University A");
JsonArray tag2 = new JsonArray();
tag2.add("Sports Specialist Student");
Map<String, String> map1 = new HashMap<>();
map1.put("tags", tag1.toString());
Map<String, String> map2 = new HashMap<>();
map2.put("tags", tag2.toString());
List<Map<String, String>> searchFilters = new ArrayList<>();
searchFilters.add(map1);
searchFilters.add(map2);
request.setSearchFilters(searchFilters);
// Perform a retrieval. Pass in the workspace ID and the RetrieveRequest.
RetrieveResponse resp = client.retrieve("Enter the actual workspace ID", request);
System.out.println(new Gson().toJson(resp.getBody()));
} catch (Exception e) {
// Handle knowledge base retrieval failures.
// This is for printing and display only. Handle exceptions with care and never ignore them directly in engineering projects.
System.out.println(e.getMessage());
}
}
}
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=YOUR_ACCESS_KEY_ID&Signature=YOUR_SIGNATURE",
"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
}
Related documents
Knowledge base user guide | |
Retrieve a knowledge base | You can call the Retrieve API to retrieve a knowledge base and return text segments. |
Calls from RAM users | RAM users (sub-accounts) must obtain the Alibaba Cloud Bailian data permissions before calling the Retrieve API. 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 troubleshoot the issue.