xref: /aosp_15_r20/external/icing/icing/result/projector.cc (revision 8b6cd535a057e39b3b86660c4aa06c99747c2136)
1 // Copyright (C) 2019 Google LLC
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //      http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include "icing/result/projector.h"
16 
17 #include <algorithm>
18 
19 #include "icing/proto/document.pb.h"
20 
21 namespace icing {
22 namespace lib {
23 
24 namespace projector {
25 
Project(const std::vector<ProjectionTree::Node> & projection_tree,DocumentProto * document)26 void Project(const std::vector<ProjectionTree::Node>& projection_tree,
27              DocumentProto* document) {
28   int num_kept = 0;
29   for (int cur_pos = 0; cur_pos < document->properties_size(); ++cur_pos) {
30     PropertyProto* prop = document->mutable_properties(cur_pos);
31     auto itr = std::find_if(projection_tree.begin(), projection_tree.end(),
32                             [&prop](const ProjectionTree::Node& node) {
33                               return node.name == prop->name();
34                             });
35     if (itr == projection_tree.end()) {
36       // Property is not present in the projection tree. Just skip it.
37       continue;
38     }
39     // This property should be kept.
40     document->mutable_properties()->SwapElements(num_kept, cur_pos);
41     ++num_kept;
42     if (itr->children.empty()) {
43       // A field mask does refer to this property, but it has no children. So
44       // we should take the entire property, with all of its
45       // subproperties/values
46       continue;
47     }
48     // The field mask refers to children of this property. Recurse through the
49     // document values that this property holds and project the children
50     // requested by this field mask.
51     for (DocumentProto& subproperty : *(prop->mutable_document_values())) {
52       Project(itr->children, &subproperty);
53     }
54   }
55   document->mutable_properties()->DeleteSubrange(
56       num_kept, document->properties_size() - num_kept);
57 }
58 
59 }  // namespace projector
60 
61 }  // namespace lib
62 }  // namespace icing
63