如何在Solr中构造查询,匹配子文档条件并求和exp值获取父文档
Solr Query to Fetch Parent Document by Child Field Conditions & Sum of Child Values
Got it, let's walk through how to build the right Solr query to get the parent document ID data1 based on your requirements. First, let's make sure we cover the prerequisites, then build the query step by step.
Prerequisites
Before we dive into the query, confirm your Solr setup meets these:
- Your schema defines the necessary fields correctly:
isParent: A string or integer field to distinguish parent docs (value1) from child docs (value2)description: A text field (set up for full-text matching)exp: A numeric field (likeintorfloat) to support sum calculations
- You're using a Solr version that supports the
child()function and Block Join queries (Solr 6.6+; 8.x and above is recommended for better nested document support)
Build the Correct Query
Your goal is to find parent docs where:
- At least one child doc has
Payrollin itsdescription - The sum of
expvalues for those matching child docs equals 7
We'll combine Block Join Parent Queries (to link parent and child docs) with a Function Query (to calculate the sum of child field values). Here's the full query:
select?q=*:* &fq={!parent which="isParent:1"}(description:Payroll) &fq=sum(child(exp,description:Payroll)):7 &fl=id
Breakdown of Each Parameter
{!parent which="isParent:1"}(description:Payroll): This Block Join filter targets parent docs that have at least one child doc matchingdescription:Payroll. Thewhichclause tells Solr that parent docs are identified byisParent:1.sum(child(exp,description:Payroll)):7: This filter calculates the sum ofexpvalues only for child docs that matchdescription:Payroll, and keeps only parent docs where this sum equals 7. If you wanted the sum of all child docs (regardless of description) plus the description match, you'd usesum(child(exp)):7instead.fl=id: This parameter tells Solr to only return the parent doc'sidfield, keeping the response clean and focused.
Expected Response
When you run the query, Solr will return the matching parent document. Here's what the response will look like (simplified):
{ "responseHeader": { "status": 0, "QTime": 2, "params": { "q": "*:*", "fq": [ "{!parent which=\"isParent:1\"}(description:Payroll)", "sum(child(exp,description:Payroll)):7" ], "fl": "id" } }, "response": { "numFound": 1, "start": 0, "docs": [ { "id": "data1" } ] } }
内容的提问来源于stack exchange,提问作者user3351289
相关产品推荐
相关产品推荐

