hey there
- User
hey there
- Assistant
Hello! How can I assist you today?
- User
- Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
hey there
Hello! How can I assist you today?
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
i'm using opensearch and flask to create an advanced search engine , i've got this function def search_videos(index_name: str, query: dict, page: int, size: int): index = index_exists(index_name) if not index: raise ValidationError({"error": "Index does not exist"})
schema = load_schema()
field_queries = get_cached_field_queries(schema)
must_conditions = []
filter_conditions = []
# Debugging: Log the incoming query
print(f"Incoming query: {query}")
for field, value in query.items():
if isinstance(value, dict):
# Handle nested fields
nested_path = field.split(".")[0]
if is_field_nested(nested_path):
nested_query = {
"nested": {
"path": nested_path,
"query": {
"bool": {
"must": [
handle_operators(
f"{nested_path}.{sub_field}", sub_value
)
for sub_field, sub_value in value.items()
]
}
},
}
}
must_conditions.append(nested_query)
else:
filter_conditions.append(handle_operators(field, value))
else:
base_field = field.split("__")[0]
query_func = field_queries.get(base_field)
if query_func and value:
if (
field.endswith("__gte")
or field.endswith("__lte")
or field.endswith("__in")
):
filter_conditions.append(handle_operators(field, value))
else:
must_conditions.append(handle_operators(field, value))
# Build the final search query
search_query = {
"query": {
"bool": {
"must": must_conditions,
"filter": filter_conditions,
}
},
"from": (page - 1) * size,
"size": size,
}
# Debugging: Log the entire constructed query before making the request
print(f"Constructed OpenSearch query: {json.dumps(search_query, indent=2)}")
opensearch_client = current_app.extensions["video_opensearch"]
try:
response = opensearch_client.search(index=index_name, body=search_query)
hits = response.get("hits", {})
documents = [hit["_source"] for hit in hits.get("hits", [])]
return SevResponse(documents)
except RequestError as e:
print(f"OpenSearch request error: {e}")
raise
def handle_operators(field: str, value): """Handle different operators for fields.""" if "__gte" in field: return {"range": {field.replace("__gte", ""): {"gte": value}}} elif "__lte" in field: return {"range": {field.replace("__lte", ""): {"lte": value}}} elif "__in" in field: return {"terms": {field.replace("__in", ""): value}} else: # Handle term and match queries if field.endswith(".keyword"): return {"term": {field: value}} else: return {"match": {field: value}}
def is_field_nested(field: str) -> bool: """Determine if the field is nested.""" return "." in field and this class class FiltringDocs(Resource): def post(self, index_name): """Search videos based on query parameters.""" schema = load_schema() payload = request.get_json()
# Extract all field paths from the schema
all_fields = extract_field_paths(schema["mappings"]["properties"])
print(f"All fields: {all_fields}")
print(f"Payload: {payload}")
query_params = {}
# Handle fields and operators
for field, value in payload.items():
if value: # Ignore empty values
if "." in field: # Check if the field is nested
nested_field = field.split(".")[0]
if nested_field not in query_params:
query_params[nested_field] = {}
# Extract sub-field and operator
sub_field = field[len(nested_field) + 1 :] # Remove the nested part
if "__" in sub_field:
sub_field, operator = sub_field.split("__", 1)
if sub_field not in query_params[nested_field]:
query_params[nested_field][sub_field] = {}
query_params[nested_field][sub_field][operator] = value
else:
query_params[nested_field][sub_field] = value
else:
query_params[field] = value
print(f"Query parameters: {query_params}")
query_params = {key: value for key, value in query_params.items() if value}
page = request.args.get("page", default=1, type=int)
size = request.args.get("size", default=10, type=int)
response = search_videos(index_name, query_params, page, size)
return response
it should accept this in payload { "video_data.ownerName": "aaa", "video_data.time__gte":"20240520000000000" }and filter the documents with it but this is what i'm getting 2024-09-10 07:39:57 Payload: {'video_data.ownerName': 'aaa', 'video_data.time__gte': '20240520000000000'} 2024-09-10 07:39:57 Query parameters: {'video_data': {'ownerName': 'aaa', 'time': {'gte': '20240520000000000'}}} 2024-09-10 07:39:57 Incoming query: {'video_data': {'ownerName': 'aaa', 'time': {'gte': '20240520000000000'}}} 2024-09-10 07:39:57 Constructed OpenSearch query: { 2024-09-10 07:39:57 "query": { 2024-09-10 07:39:57 "bool": { 2024-09-10 07:39:57 "must": [], 2024-09-10 07:39:57 "filter": [ 2024-09-10 07:39:57 { 2024-09-10 07:39:57 "match": { 2024-09-10 07:39:57 "video_data": { 2024-09-10 07:39:57 "ownerName": "aaa", 2024-09-10 07:39:57 "time": { 2024-09-10 07:39:57 "gte": "20240520000000000" 2024-09-10 07:39:57 } 2024-09-10 07:39:57 } 2024-09-10 07:39:57 } 2024-09-10 07:39:57 } 2024-09-10 07:39:57 ] 2024-09-10 07:39:57 } 2024-09-10 07:39:57 }, 2024-09-10 07:39:57 "from": 0, 2024-09-10 07:39:57 "size": 10 2024-09-10 07:39:57 }
The issue you're encountering seems to arise from how your query is being constructed and processed. The main problem is that the nested structure (video_data.ownerName and video_data.time__gte) in your payload isn't being correctly parsed into OpenSearch's required nested query format. Instead, it's being processed as a match query for the entire video_data object, which isn't correct.
Here's a breakdown of potential fixes to ensure your query is correctly structured to handle nested fields:
Nested Query Construction:
handle_operators and main query construction, ensure that nested fields construct queries with the "nested": {...} structure. It seems your current setup is trying to create a match query instead, which isn't what you want for deeply nested data.Update your handle_operators function:
def handle_operators(field: str, value):
"""Handle different operators for fields."""
if "__gte" in field or "__lte" in field or "__in" in field:
field_name, operator = field.rsplit('__', 1)
if operator == "gte":
return {"range": {field_name: {"gte": value}}}
elif operator == "lte":
return {"range": {field_name: {"lte": value}}}
elif operator == "in":
return {"terms": {field_name: value}}
else:
if ".keyword" in field or isinstance(value, str):
return {"term": {field: value}}
else:
return {"match": {field: value}}
search_videos:
nested query structure.for field, value in query.items():
if isinstance(value, dict):
for sub_field, sub_value in value.items():
if field in schema['properties'] and schema['properties'][field].get('type') == 'nested':
nested_query = {
"nested": {
"path": field,
"query": {
"bool": {
"must": [
handle_operators(f"{field}.{sub_field}", sub_value)
]
}
}
}
}
must_conditions.append(nested_query)
else:
filter_conditions.append(handle_operators(f"{field}.{sub_field}", sub_value))
else:
# Base fields, non-nested
must_conditions.append(handle_operators(field, value))
Schema Inspection (Optional):
Logging and Debugging:
After making these changes, run your code again and inspect both input and constructed queries to ensure they match expected OpenSearch formats for nested objects. If the issue persists, you might want to check OpenSearch's specific documentation for nuances about handling nested queries.
Not yet included in a published release.