├── .gitignore ├── LICENSE ├── NOTICE ├── README.md ├── build.sh ├── build.xml ├── configs ├── README ├── example.csv ├── feed.sh ├── restart-solr-dbg.sh ├── restart-solr.sh └── solr │ ├── core0 │ ├── conf │ │ ├── schema.xml │ │ └── solrconfig.xml │ └── core.properties │ ├── knowledge-graph │ ├── conf │ │ ├── mapping-FoldToASCII.txt │ │ ├── mapping-ISOLatin1Accent.txt │ │ ├── schema.xml │ │ └── solrconfig.xml │ └── core.properties │ └── solr.xml ├── knowledge-graph ├── .gitignore ├── pom.xml └── src │ ├── main │ └── java │ │ └── com │ │ └── careerbuilder │ │ └── search │ │ └── relevancy │ │ ├── FieldChecker.java │ │ ├── KnowledgeGraphHandler.java │ │ ├── NodeContext.java │ │ ├── RecursionOp.java │ │ ├── RequestTreeRecurser.java │ │ ├── RequestValidator.java │ │ ├── generation │ │ ├── FacetFieldAdapter.java │ │ └── NodeGenerator.java │ │ ├── model │ │ ├── Error.java │ │ ├── KnowledgeGraphRequest.java │ │ ├── KnowledgeGraphResponse.java │ │ ├── ParameterSet.java │ │ ├── RequestNode.java │ │ ├── ResponseNode.java │ │ ├── ResponseValue.java │ │ └── SortType.java │ │ ├── normalization │ │ └── NodeNormalizer.java │ │ ├── responsewriter │ │ ├── KnowledgeGraphResponseWriter.java │ │ └── ResponseValueSerializer.java │ │ ├── scoring │ │ ├── BackupScorer.java │ │ ├── BinomialStrategy.java │ │ ├── NodeScorer.java │ │ ├── QueryRunnerFactory.java │ │ └── ScoreNormalizer.java │ │ ├── threadpool │ │ ├── ThreadPool.java │ │ └── ThreadPoolHolder.java │ │ ├── utility │ │ ├── MapUtility.java │ │ ├── ParseUtility.java │ │ ├── ResponseUtility.java │ │ └── SortUtility.java │ │ └── waitable │ │ ├── AggregationWaitable.java │ │ ├── QueryWaitable.java │ │ └── Waitable.java │ └── test │ └── java │ └── com │ └── careerbuilder │ └── search │ └── relevancy │ ├── Model │ ├── ResponseNodeTest.java │ └── ResponseValueTest.java │ ├── RequestTreeRecurserTest.java │ ├── RequestValidatorTest.java │ ├── generation │ ├── FacetFieldAdapterTest.java │ └── NodeGeneratorTest.java │ ├── normalization │ └── NodeNormalizerTest.java │ ├── responsewriter │ ├── KnowledgeGraphResponseWriterTest.java │ └── ResponseValueSerializerTest.java │ ├── scoring │ ├── BackupScorerTest.java │ ├── NodeScorerTest.java │ ├── QueryWaitableFactoryTest.java │ ├── RelatednessStrategyTest.java │ └── ScoreNormalizerTest.java │ ├── threadpool │ ├── MapUtilityTest.java │ └── ThreadPoolTest.java │ ├── utility │ └── ResponseUtilityTest.java │ └── waitable │ ├── AggregationWaitableTest.java │ └── QueryWaitableTest.java ├── patches └── lucene_solr_5_1_0.patch └── rebuild.sh /.gitignore: -------------------------------------------------------------------------------- 1 | deploy 2 | lucene-solr 3 | cores/ 4 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm 5 | 6 | *.iml 7 | 8 | ## Directory-based project format: 9 | .idea/ 10 | # if you remove the above rule, at least ignore the following: 11 | 12 | # User-specific stuff: 13 | # .idea/workspace.xml 14 | # .idea/tasks.xml 15 | # .idea/dictionaries 16 | 17 | # Sensitive or high-churn files: 18 | # .idea/dataSources.ids 19 | # .idea/dataSources.xml 20 | # .idea/sqlDataSources.xml 21 | # .idea/dynamic.xml 22 | # .idea/uiDesigner.xml 23 | 24 | # Gradle: 25 | # .idea/gradle.xml 26 | # .idea/libraries 27 | 28 | # Mongo Explorer plugin: 29 | # .idea/mongoSettings.xml 30 | 31 | ## File-based project format: 32 | *.ipr 33 | *.iws 34 | 35 | ## Plugin-specific files: 36 | 37 | # IntelliJ 38 | /out/ 39 | 40 | # mpeltonen/sbt-idea plugin 41 | .idea_modules/ 42 | 43 | # JIRA plugin 44 | atlassian-ide-plugin.xml 45 | 46 | # Crashlytics plugin (for Android Studio and IntelliJ) 47 | com_crashlytics_export_strings.xml 48 | crashlytics.properties 49 | crashlytics-build.properties 50 | 51 | #Maven 52 | target/ 53 | pom.xml.tag 54 | pom.xml.releaseBackup 55 | pom.xml.versionsBackup 56 | pom.xml.next 57 | release.properties 58 | dependency-reduced-pom.xml 59 | buildNumber.properties 60 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright 2016 Careerbuilder LLC 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | Semantic Knowledge Graph 2 | Copyright 2016 CareerBuilder, LLC 3 | This product includes software developed at CareerBuilder, LLC (http://www.careerbuilder.com) 4 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | #Semantic Knowledge Graph 2 | *A graph structure, build automatically from a corpus of data, for traversing and measuring relationships within a domain* 3 | 4 | The Semantic Knowledge Graph serves as a data scientist's toolkit, allowing you to discover and compare any entities modeled within a corpus of data from any domain. For example, if you indexed a corpus of job postings, you could figure out what the most related job titles are for the phrase "account manager", and subsequently what the top skills are for each of those job titles. You can also use the system to rank a list of entities or keywords based upon their statistical relationship with any other group of entities or terms, and you can traverse these relationships any number of levels deep. The Semantic Knowledge Graph will allow you to slice and dice the universe of terms and entites represented within your corpus in order to discover as many of these insights as you have the time and curiosity to pursue. 5 | 6 | The Semantic Knowledge Graph is packaged as a request handler plugin for the popular Apache Solr search engine. Fundamentally, you must create a schema representing your corpus of data (from any domain), send the corpus of documents to Solr (script to do this is included), and then you can send queries to the Semantic Knowledge Graph request handler to discover and/or score relationships. 7 | 8 | ## License and Citation 9 | 10 | The Semantic Knowledge Graph source code is licensed under the [ASL 2.0 License](https://github.com/careerbuilder/semantic-knowledge-graph/blob/master/LICENSE). 11 | 12 | A research paper describing the Semantic Knowledge Graph is being published in the proceedings of the 2016 IEEE 3rd International Conference on Data Science and Advanced Analytics: 13 | 14 | [The Semantic Knowledge Graph: A compact, auto-generated model for real-time traversal and ranking of any relationship within a domain](https://arxiv.org/abs/1609.00464). 15 | 16 | Please cite the Semantic Knowledge Graph in your publications if it helps your research: 17 | 18 | @article{grainger2016SemanticKnowledgeGraph, 19 | Author = {Grainger, Trey and AlJadda, Khalifeh and Korayem, Mohammed and Smith, Andries}, 20 | Journal = {arXiv preprint arXiv:1609.00464}, 21 | Title = {The Semantic Knowledge Graph: A compact, auto-generated model for real-time traversal and ranking of any relationship within a domain}, 22 | Year = {2016} 23 | } 24 | 25 | #Usage (examples from the job search domain): 26 | 27 | *Request:* 28 | ``` 29 | curl -X POST http://localhost:8983/solr/skg/rel \ 30 | -H "Content-Type: application/json" \ 31 | -d \ 32 | '{ 33 | "queries": [ 34 | "keywords:\"data scientist\"" 35 | ], 36 | "compare": [ 37 | { 38 | "type": "jobtitle", 39 | "limit": 1, 40 | "compare": [ 41 | { 42 | "type": "skills", 43 | "limit": 5, 44 | "discover_values": true, 45 | "values": [ 46 | "java (programming language)" 47 | ] 48 | } 49 | ] 50 | } 51 | ] 52 | }' 53 | ``` 54 | 55 | Response: 56 | ``` 57 | { "data": [ 58 | { 59 | "type": "jobtitle", 60 | "values": [ 61 | { 62 | "id": "", 63 | "name": "Data Scientist", 64 | "relatedness": 0.989, 65 | "popularity": 86.0, 66 | "foreground_popularity": 86.0, 67 | "background_popularity": 142.0, 68 | "compare": [ 69 | { 70 | "type": "skills.v3", 71 | "values": [ 72 | { 73 | "id": "", 74 | "name": "Machine Learning", 75 | "relatedness": 0.97286, 76 | "popularity": 54.0, 77 | "foreground_popularity": 54.0, 78 | "background_popularity": 356.0 79 | }, 80 | { 81 | "id": "", 82 | "name": "Predictive Modelling", 83 | "relatedness": 0.94565, 84 | "popularity": 27.0, 85 | "foreground_popularity": 27.0, 86 | "background_popularity": 384.0 87 | }, 88 | { 89 | "id": "", 90 | "name": "Artificial Neural Networks", 91 | "relatedness": 0.94416, 92 | "popularity": 10.0, 93 | "foreground_popularity": 10.0, 94 | "background_popularity": 57.0 95 | }, 96 | { 97 | "id": "", 98 | "name": "Apache Hadoop", 99 | "relatedness": 0.94274, 100 | "popularity": 50.0, 101 | "foreground_popularity": 50.0, 102 | "background_popularity": 1418.0 103 | }, 104 | { 105 | "id": "", 106 | "name": "Java (Programming Language)", 107 | "relatedness": 0.76606, 108 | "popularity": 37.0, 109 | "foreground_popularity": 37.0, 110 | "background_popularity": 17442.0 111 | } 112 | ] 113 | } 114 | ] 115 | } 116 | ] 117 | } 118 | ] 119 | } 120 | ``` 121 | 122 | #Available Request Options 123 | **queries** String[] 124 | A set of Solr queries which will be used to generate entities for scoring. If no foreground queries are supplied, these queries will also be used to score the entities. Multiple queries are merged to find the intersection between them (equivalent of a boolean AND query). See the types parameter for query field types. 125 | 126 | Note: the default operator between keywords is OR. If you wish to search for multiple words as a phrase, wrap them in quotes. If you want to make all keywords required, add a + before them or insert an AND between them: 127 | senior java developer = senior OR java OR developer 128 | +senior +java +developer = senior AND java AND developer 129 | "senior java developer" = Exact phrase match for all three words in order 130 | "senior" "java developer" = senior OR "java developer" 131 | 132 | **compare** Object[] 133 | An arbitrarily nested (recursive) list of objects corresponding to entity types to generate and score. Each item in the comparison list will generate scored lists of values based upon the requested relationship to their containing parent. 134 | 135 | **type** String 136 | The type of entity to generate or score. These types correspond to the fields in your Solr schema.xml 137 | 138 | **sort** optional String 139 | The field to sort on. Supported fields include: 140 | relatedness (statistical correlation) 141 | popularity (count per 1 million documents) 142 | foreground_popularity (popularity within the foreground query) 143 | background_popularity (popularity within the background query) 144 | 145 | Defaults to relatedness. 146 | 147 | **limit** optional integer 148 | The limit on the result set size. Defaults to 1. 149 | 150 | **values** optional String[] 151 | A set of values to score. Only exact id or name matches are will be scored correctly. Note: unless passed-in values do not meet the minimum popularity requirement, passed-in values override generated values in the result set. For example, if three values are passed in and a limit of ten is set, the top seven generated values will be returned along with the three passed-in values, regardless of scores or popularity of the passed-in values. 152 | 153 | **discover_values** optional boolean 154 | Whether or not to generate values. If set to true, the query in the queries parameter will be used to automatically generate a set of values to score. Defaults to "true" if no values are passed in in the values parameter, "false" otherwise. 155 | 156 | **compare** optional Object[] 157 | A list of nested request objects. For each value returned for this entity type, all nested request object entity types will be generated and scored. Note: the "queries" and "foreground_queries" parameters are combined with the parent entity value when generating / scoring nested entities. 158 | 159 | **foreground_queries** optional String[] 160 | If supplied, a set of Solr queries used to score the results generated using the queries in the queries parameter. The relatedness score will measure statistical skewedness toward the foreground_queries queries merged together using AND. Defaults to the value of the queries parameter. See the types parameter for query field types. 161 | 162 | **background_queries** optional String[] 163 | If supplied, a set of Solr queries used to score the results generated using the queries in the queries parameter. The relatedness score will measure statistical skewedness away from the background_queries queries merged together using AND. Defaults to match all documents. See the types parameter for query field types. 164 | 165 | **min_popularity** optional double 166 | The minimum popularity of returned results (assuming exactly 1 million total documents). Results which have a popularity, foreground popularity, or background popularity lower than min_popularity out of 1 million are omitted. Defaults to at least 1 hit per million documents. 167 | 168 | **normalize_values** optional boolean 169 | Whether the API should attempt to find ids and names for passed-in values. If false, the API will return passed-in values in the name field without regard to whether they represent an id or name for an entity. Turning normalization off may boost performance. Defaults to "true." 170 | 171 | #Building and Running 172 | The easiest way to build the Semantic Knowledg Graph is to run the `build.sh` script in the root directory of the project (or `rebuild.sh`, which will build and launch an Apache Solr instance with the Semantic Knowledge Graph configured). The final application will be found in the `deploy` directory, and you can launch it using the `restart-solr.sh` script found in that directory. You can simply copy this `deploy` folder to your production environment and run the `restart-solr.sh` script to launch the service. By default, you can hit it at `http://localhost:8983/solr/knowledge-graph/rel`. See the example in the Examples section above for usage. 173 | 174 | #Using the System 175 | Once the Semantic Knowledge Graph project has been built, you need to indexing a corpus of data through it by running the `feed.sh` script. The fields you include in your corpus should correspond to the fields defined in your Solr `schema.xml` found in the `deploy/solr/knowledge-graph/conf` directory. 176 | -------------------------------------------------------------------------------- /build.sh: -------------------------------------------------------------------------------- 1 | ant pull 2 | cd lucene-solr 3 | ant ivy-bootstrap 4 | cd ../knowledge-graph/ 5 | mvn clean 6 | mvn package 7 | cd ../ 8 | ant package 9 | cd deploy 10 | chmod +x restart-solr.sh 11 | chmod +x restart-solr-dbg.sh 12 | chmod +x feed.sh 13 | chmod +x solr/bin/solr 14 | -------------------------------------------------------------------------------- /build.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | -------------------------------------------------------------------------------- /configs/README: -------------------------------------------------------------------------------- 1 | To feed the example, run "./feed.sh ./ knowledge-graph" in this directory. 2 | 3 | Example query: 4 | {"queries":["field.v1:\"data scientist\""],"min_popularity":0.0,"compare":[{"type":"field.v1","limit":5, "sort":"relatedness"}]} 5 | -------------------------------------------------------------------------------- /configs/example.csv: -------------------------------------------------------------------------------- 1 | id,content,field.v1,field.v1.id-name 2 | 1,This is an example,1|data scientist,1^data scientist 3 | 2,data analytics,2|data analytics|1|data scientist,2^data analytics|1^data scientist 4 | 3,data analytics,2|data analytics|1|data scientist,2^data analytics|1^data scientist 5 | 4,data analytics,2|data analytics|1|data scientist,2^data analytics|1^data scientist 6 | 5,data analytics,2|data analytics|1|data scientist,2^data analytics|1^data scientist 7 | 6,something else,3|machine learning,3^machine learning 8 | 7,something else,3|machine learning,3^machine learning 9 | 8,something else,3|machine learning,3^machine learning 10 | 9,something else,3|machine learning,3^machine learning 11 | 10,something else,3|machine learning,3^machine learning 12 | -------------------------------------------------------------------------------- /configs/feed.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | CSVFOLDER=$1 3 | CORENAME=$2 4 | 5 | for file in $CSVFOLDER/*.csv 6 | do 7 | curl http://localhost:8983/solr/$CORENAME/update?commit=true --data-binary @$file -H 'Content-type:text/csv' 8 | done 9 | 10 | -------------------------------------------------------------------------------- /configs/restart-solr-dbg.sh: -------------------------------------------------------------------------------- 1 | solr/bin/solr restart -m 5g -a "-server -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=8984" 2 | -------------------------------------------------------------------------------- /configs/restart-solr.sh: -------------------------------------------------------------------------------- 1 | solr/bin/solr restart -m 5g -a "-server" 2 | -------------------------------------------------------------------------------- /configs/solr/core0/conf/schema.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | id 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /configs/solr/core0/conf/solrconfig.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4.7 4 | ${solr.data.dir:} 5 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | false 15 | 1 16 | 17 | 18 | 19 | 20 | 21 | 22 | solrpingquery 23 | 24 | 25 | all 26 | 27 | server-enabled 28 | 29 | 30 | 33 | 34 | 37 | 38 | 40 | 41 | 42 | 45 | 46 | explicit 47 | text 48 | 49 | 50 | 51 | 52 | *:* 53 | 54 | 55 | 56 | -------------------------------------------------------------------------------- /configs/solr/core0/core.properties: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/careerbuilder/semantic-knowledge-graph/047be46655df96ff4b6e1c790436686a60f494f6/configs/solr/core0/core.properties -------------------------------------------------------------------------------- /configs/solr/knowledge-graph/conf/mapping-ISOLatin1Accent.txt: -------------------------------------------------------------------------------- 1 | # The ASF licenses this file to You under the Apache License, Version 2.0 2 | # (the "License"); you may not use this file except in compliance with 3 | # the License. You may obtain a copy of the License at 4 | # 5 | # http://www.apache.org/licenses/LICENSE-2.0 6 | # 7 | # Unless required by applicable law or agreed to in writing, software 8 | # distributed under the License is distributed on an "AS IS" BASIS, 9 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10 | # See the License for the specific language governing permissions and 11 | # limitations under the License. 12 | 13 | # Syntax: 14 | # "source" => "target" 15 | # "source".length() > 0 (source cannot be empty.) 16 | # "target".length() >= 0 (target can be empty.) 17 | 18 | # example: 19 | # "À" => "A" 20 | # "\u00C0" => "A" 21 | # "\u00C0" => "\u0041" 22 | # "ß" => "ss" 23 | # "\t" => " " 24 | # "\n" => "" 25 | 26 | # À => A 27 | "\u00C0" => "A" 28 | 29 | # Á => A 30 | "\u00C1" => "A" 31 | 32 | #  => A 33 | "\u00C2" => "A" 34 | 35 | # à => A 36 | "\u00C3" => "A" 37 | 38 | # Ä => A 39 | "\u00C4" => "A" 40 | 41 | # Å => A 42 | "\u00C5" => "A" 43 | 44 | # Æ => AE 45 | "\u00C6" => "AE" 46 | 47 | # Ç => C 48 | "\u00C7" => "C" 49 | 50 | # È => E 51 | "\u00C8" => "E" 52 | 53 | # É => E 54 | "\u00C9" => "E" 55 | 56 | # Ê => E 57 | "\u00CA" => "E" 58 | 59 | # Ë => E 60 | "\u00CB" => "E" 61 | 62 | # Ì => I 63 | "\u00CC" => "I" 64 | 65 | # Í => I 66 | "\u00CD" => "I" 67 | 68 | # Î => I 69 | "\u00CE" => "I" 70 | 71 | # Ï => I 72 | "\u00CF" => "I" 73 | 74 | # IJ => IJ 75 | "\u0132" => "IJ" 76 | 77 | # Ð => D 78 | "\u00D0" => "D" 79 | 80 | # Ñ => N 81 | "\u00D1" => "N" 82 | 83 | # Ò => O 84 | "\u00D2" => "O" 85 | 86 | # Ó => O 87 | "\u00D3" => "O" 88 | 89 | # Ô => O 90 | "\u00D4" => "O" 91 | 92 | # Õ => O 93 | "\u00D5" => "O" 94 | 95 | # Ö => O 96 | "\u00D6" => "O" 97 | 98 | # Ø => O 99 | "\u00D8" => "O" 100 | 101 | # Œ => OE 102 | "\u0152" => "OE" 103 | 104 | # Þ 105 | "\u00DE" => "TH" 106 | 107 | # Ù => U 108 | "\u00D9" => "U" 109 | 110 | # Ú => U 111 | "\u00DA" => "U" 112 | 113 | # Û => U 114 | "\u00DB" => "U" 115 | 116 | # Ü => U 117 | "\u00DC" => "U" 118 | 119 | # Ý => Y 120 | "\u00DD" => "Y" 121 | 122 | # Ÿ => Y 123 | "\u0178" => "Y" 124 | 125 | # à => a 126 | "\u00E0" => "a" 127 | 128 | # á => a 129 | "\u00E1" => "a" 130 | 131 | # â => a 132 | "\u00E2" => "a" 133 | 134 | # ã => a 135 | "\u00E3" => "a" 136 | 137 | # ä => a 138 | "\u00E4" => "a" 139 | 140 | # å => a 141 | "\u00E5" => "a" 142 | 143 | # æ => ae 144 | "\u00E6" => "ae" 145 | 146 | # ç => c 147 | "\u00E7" => "c" 148 | 149 | # è => e 150 | "\u00E8" => "e" 151 | 152 | # é => e 153 | "\u00E9" => "e" 154 | 155 | # ê => e 156 | "\u00EA" => "e" 157 | 158 | # ë => e 159 | "\u00EB" => "e" 160 | 161 | # ì => i 162 | "\u00EC" => "i" 163 | 164 | # í => i 165 | "\u00ED" => "i" 166 | 167 | # î => i 168 | "\u00EE" => "i" 169 | 170 | # ï => i 171 | "\u00EF" => "i" 172 | 173 | # ij => ij 174 | "\u0133" => "ij" 175 | 176 | # ð => d 177 | "\u00F0" => "d" 178 | 179 | # ñ => n 180 | "\u00F1" => "n" 181 | 182 | # ò => o 183 | "\u00F2" => "o" 184 | 185 | # ó => o 186 | "\u00F3" => "o" 187 | 188 | # ô => o 189 | "\u00F4" => "o" 190 | 191 | # õ => o 192 | "\u00F5" => "o" 193 | 194 | # ö => o 195 | "\u00F6" => "o" 196 | 197 | # ø => o 198 | "\u00F8" => "o" 199 | 200 | # œ => oe 201 | "\u0153" => "oe" 202 | 203 | # ß => ss 204 | "\u00DF" => "ss" 205 | 206 | # þ => th 207 | "\u00FE" => "th" 208 | 209 | # ù => u 210 | "\u00F9" => "u" 211 | 212 | # ú => u 213 | "\u00FA" => "u" 214 | 215 | # û => u 216 | "\u00FB" => "u" 217 | 218 | # ü => u 219 | "\u00FC" => "u" 220 | 221 | # ý => y 222 | "\u00FD" => "y" 223 | 224 | # ÿ => y 225 | "\u00FF" => "y" 226 | 227 | # ff => ff 228 | "\uFB00" => "ff" 229 | 230 | # fi => fi 231 | "\uFB01" => "fi" 232 | 233 | # fl => fl 234 | "\uFB02" => "fl" 235 | 236 | # ffi => ffi 237 | "\uFB03" => "ffi" 238 | 239 | # ffl => ffl 240 | "\uFB04" => "ffl" 241 | 242 | # ſt => ft 243 | "\uFB05" => "ft" 244 | 245 | # st => st 246 | "\uFB06" => "st" 247 | -------------------------------------------------------------------------------- /configs/solr/knowledge-graph/conf/schema.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | id 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /configs/solr/knowledge-graph/conf/solrconfig.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5.10 4 | 5 | ../../../cores/skg/data 6 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 100000 16 | 17 | 18 | 19 | ${solr.ulog.dir:} 20 | 21 | 22 | 23 | 24 | false 25 | 2 26 | 27 | 28 | 29 | 30 | 31 | explicit 32 | true 33 | 10 34 | text 35 | AND 36 | json 37 | true 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | content 46 | edismax 47 | 48 | 49 | 51 | content 52 | skg 53 | 54 | id-name 55 | 57 | id 58 | 59 | 60 | 61 | 62 | 63 | true 64 | " 65 | | 66 | true 67 | " 68 | | 69 | 70 | 71 | 72 | 73 | 76 | 77 | 80 | 81 | 83 | 84 | 85 | 86 | 87 | solrpingquery 88 | 89 | 90 | all 91 | 92 | server-enabled 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | true 106 | false 107 | 108 | 109 | terms 110 | 111 | 112 | 113 | 114 | 115 | *:* 116 | 117 | 118 | 119 | -------------------------------------------------------------------------------- /configs/solr/knowledge-graph/core.properties: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/careerbuilder/semantic-knowledge-graph/047be46655df96ff4b6e1c790436686a60f494f6/configs/solr/knowledge-graph/core.properties -------------------------------------------------------------------------------- /configs/solr/solr.xml: -------------------------------------------------------------------------------- 1 | 2 | 18 | 19 | 28 | 29 | 30 | 31 | 32 | ${host:} 33 | ${jetty.port:8983} 34 | ${hostContext:solr} 35 | ${zkClientTimeout:30000} 36 | ${genericCoreNodeNames:true} 37 | 38 | 39 | 41 | ${socketTimeout:0} 42 | ${connTimeout:0} 43 | 44 | 45 | 46 | -------------------------------------------------------------------------------- /knowledge-graph/.gitignore: -------------------------------------------------------------------------------- 1 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm 2 | 3 | *.iml 4 | 5 | ## Directory-based project format: 6 | .idea/ 7 | # if you remove the above rule, at least ignore the following: 8 | 9 | # User-specific stuff: 10 | # .idea/workspace.xml 11 | # .idea/tasks.xml 12 | # .idea/dictionaries 13 | 14 | # Sensitive or high-churn files: 15 | # .idea/dataSources.ids 16 | # .idea/dataSources.xml 17 | # .idea/sqlDataSources.xml 18 | # .idea/dynamic.xml 19 | # .idea/uiDesigner.xml 20 | 21 | # Gradle: 22 | # .idea/gradle.xml 23 | # .idea/libraries 24 | 25 | # Mongo Explorer plugin: 26 | # .idea/mongoSettings.xml 27 | 28 | ## File-based project format: 29 | *.ipr 30 | *.iws 31 | 32 | ## Plugin-specific files: 33 | 34 | # IntelliJ 35 | /out/ 36 | 37 | # mpeltonen/sbt-idea plugin 38 | .idea_modules/ 39 | 40 | # JIRA plugin 41 | atlassian-ide-plugin.xml 42 | 43 | # Crashlytics plugin (for Android Studio and IntelliJ) 44 | com_crashlytics_export_strings.xml 45 | crashlytics.properties 46 | crashlytics-build.properties 47 | 48 | #Maven 49 | target/ 50 | pom.xml.tag 51 | pom.xml.releaseBackup 52 | pom.xml.versionsBackup 53 | pom.xml.next 54 | release.properties 55 | dependency-reduced-pom.xml 56 | buildNumber.properties 57 | -------------------------------------------------------------------------------- /knowledge-graph/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 4.0.0 7 | 8 | com.careerbuilder.relevancy 9 | knowledge-graph 10 | 1.0-SNAPSHOT 11 | jar 12 | 13 | 14 | semantic_knowledge_graph 15 | Ranks tags using corpus of tagged data 16 | 2016 17 | 18 | 19 | UTF-8 20 | 5.1.0 21 | 22 | 23 | 24 | 2.2.1 25 | 26 | 27 | 28 | 29 | 30 | org.apache.solr 31 | solr-test-framework 32 | ${solr.version} 33 | test 34 | 35 | 36 | org.apache.lucene 37 | lucene-test-framework 38 | ${solr.version} 39 | test 40 | 41 | 42 | 43 | org.apache.solr 44 | solr-core 45 | ${solr.version} 46 | 47 | 48 | org.slf4j 49 | slf4j-jdk14 50 | 51 | 52 | org.slf4j 53 | slf4j-log4j12 54 | 55 | 56 | log4j 57 | log4j 58 | 59 | 60 | 61 | 62 | 63 | org.apache.lucene 64 | lucene-core 65 | ${solr.version} 66 | 67 | 68 | 69 | org.apache.commons 70 | commons-lang3 71 | 3.4 72 | 73 | 74 | com.google.code.gson 75 | gson 76 | 1.7.1 77 | 78 | 79 | com.carrotsearch 80 | hppc 81 | 0.5.2 82 | 83 | 84 | 85 | 86 | org.slf4j 87 | slf4j-api 88 | 1.7.7 89 | 90 | 91 | org.slf4j 92 | jcl-over-slf4j 93 | 1.7.7 94 | 95 | 96 | ch.qos.logback 97 | logback-classic 98 | 1.1.2 99 | runtime 100 | true 101 | 102 | 103 | junit 104 | junit 105 | 4.11 106 | 107 | 108 | org.jmockit 109 | jmockit 110 | 1.8 111 | 112 | 113 | 114 | 115 | 116 | 117 | org.apache.maven.plugins 118 | maven-compiler-plugin 119 | 3.1 120 | 121 | 1.8 122 | 1.8 123 | 124 | 125 | 126 | 127 | org.apache.maven.plugins 128 | maven-jar-plugin 129 | 2.4 130 | 131 | 132 | 133 | true 134 | true 135 | 136 | 137 | 138 | 139 | 140 | org.apache.maven.plugins 141 | maven-shade-plugin 142 | 1.6 143 | 144 | 145 | package 146 | 147 | shade 148 | 149 | 150 | 151 | 152 | com.google.code.gson:gson 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | -------------------------------------------------------------------------------- /knowledge-graph/src/main/java/com/careerbuilder/search/relevancy/FieldChecker.java: -------------------------------------------------------------------------------- 1 | package com.careerbuilder.search.relevancy; 2 | 3 | import org.apache.solr.common.SolrException; 4 | import org.apache.solr.request.SolrQueryRequest; 5 | 6 | public class FieldChecker { 7 | 8 | public static void checkField(SolrQueryRequest req, String inputField, String facetField) { 9 | try { 10 | req.getCore() 11 | .getLatestSchema() 12 | .getField(facetField).getName(); 13 | } catch (SolrException e) { 14 | throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, 15 | "Values of type \"" + inputField + "\" cannot be generated automatically or normalized " + 16 | "(adapted as \"" + facetField + "\")"); 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /knowledge-graph/src/main/java/com/careerbuilder/search/relevancy/KnowledgeGraphHandler.java: -------------------------------------------------------------------------------- 1 | package com.careerbuilder.search.relevancy; 2 | 3 | import com.careerbuilder.search.relevancy.model.ParameterSet; 4 | import com.careerbuilder.search.relevancy.model.KnowledgeGraphRequest; 5 | import com.careerbuilder.search.relevancy.model.KnowledgeGraphResponse; 6 | import com.google.common.io.CharStreams; 7 | import com.google.gson.Gson; 8 | import org.apache.lucene.analysis.util.ResourceLoader; 9 | import org.apache.solr.common.SolrException; 10 | import org.apache.solr.common.util.ContentStream; 11 | import org.apache.solr.common.util.NamedList; 12 | import org.apache.solr.handler.RequestHandlerBase; 13 | import org.apache.solr.request.SolrQueryRequest; 14 | import org.apache.solr.response.SolrQueryResponse; 15 | 16 | import java.io.IOException; 17 | import java.io.Reader; 18 | import java.util.Iterator; 19 | 20 | 21 | public class KnowledgeGraphHandler extends RequestHandlerBase 22 | { 23 | private ResourceLoader loader; 24 | 25 | @Override 26 | public void init(NamedList args) { 27 | super.init(args); 28 | } 29 | 30 | @Override 31 | public void handleRequestBody(SolrQueryRequest solrReq, SolrQueryResponse solrRsp) 32 | throws Exception { 33 | KnowledgeGraphRequest request = parsePost(solrReq); 34 | new RequestValidator(solrReq, request).validate(); 35 | ParameterSet parameterSet = new ParameterSet(solrReq.getParams(), defaults, invariants); 36 | NodeContext context = new NodeContext(request, solrReq, parameterSet); 37 | RequestTreeRecurser recurser = new RequestTreeRecurser(context); 38 | KnowledgeGraphResponse response = new KnowledgeGraphResponse(); 39 | response.data = recurser.score(); 40 | solrRsp.add("relatednessResponse", response); 41 | } 42 | 43 | private KnowledgeGraphRequest parsePost(SolrQueryRequest request) throws IOException { 44 | String inputString = getPostString(request); 45 | try { 46 | return new Gson().fromJson(inputString, KnowledgeGraphRequest.class); 47 | } catch (Exception e) { 48 | throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, e.getMessage()); 49 | } 50 | } 51 | 52 | private String getPostString(SolrQueryRequest request) throws IOException { 53 | Reader inputReader = null; 54 | Iterable streams = request.getContentStreams(); 55 | if (streams != null) { 56 | Iterator iter = streams.iterator(); 57 | if (iter.hasNext()) { 58 | inputReader = iter.next().getReader(); 59 | } 60 | if (iter.hasNext()) { 61 | throwWithClassName(" does not support multiple ContentStreams"); 62 | } 63 | } 64 | if (inputReader == null) { 65 | throwWithClassName(" requires POST data"); 66 | } 67 | String inputString; 68 | inputString = CharStreams.toString(inputReader); 69 | inputReader.close(); 70 | if(inputString.equals("") || inputString == null) { 71 | throwWithClassName(" requires POST data"); 72 | } 73 | return inputString; 74 | } 75 | 76 | private void throwWithClassName(String msgAfterClassName) { 77 | throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, 78 | getClass().getSimpleName()+ msgAfterClassName); 79 | } 80 | 81 | //////////////////////// SolrInfoMBeans methods ////////////////////// 82 | 83 | @Override 84 | public String getDescription() 85 | { 86 | return "Ranks tags using corpus of tagged data"; 87 | } 88 | 89 | @Override 90 | public String getSource() { 91 | return "$Source$"; 92 | } 93 | 94 | @Override 95 | public String getVersion() { 96 | return "$Revision$"; 97 | } 98 | 99 | 100 | } -------------------------------------------------------------------------------- /knowledge-graph/src/main/java/com/careerbuilder/search/relevancy/NodeContext.java: -------------------------------------------------------------------------------- 1 | package com.careerbuilder.search.relevancy; 2 | 3 | import com.careerbuilder.search.relevancy.model.ParameterSet; 4 | import com.careerbuilder.search.relevancy.model.KnowledgeGraphRequest; 5 | import com.careerbuilder.search.relevancy.utility.ParseUtility; 6 | import org.apache.lucene.search.Query; 7 | import org.apache.solr.request.SolrQueryRequest; 8 | import org.apache.solr.search.*; 9 | 10 | import java.io.IOException; 11 | import java.util.List; 12 | 13 | public class NodeContext { 14 | 15 | public KnowledgeGraphRequest request; 16 | public SolrQueryRequest req; 17 | public ParameterSet parameterSet; 18 | public List queries; 19 | public List fgQueries; 20 | public List bgQueries; 21 | public DocListAndSet queryDomainList; 22 | public DocSet queryDomain; 23 | public DocSet fgDomain; 24 | public DocSet bgDomain; 25 | 26 | @Deprecated 27 | public NodeContext(KnowledgeGraphRequest request) 28 | { 29 | this.request = request; 30 | } 31 | 32 | @Deprecated 33 | public NodeContext(ParameterSet parameterSet) 34 | { 35 | this.parameterSet = parameterSet; 36 | } 37 | 38 | public NodeContext(KnowledgeGraphRequest request, SolrQueryRequest req, ParameterSet parameterSet) throws IOException 39 | { 40 | this.request = request; 41 | this.req = req; 42 | this.parameterSet = parameterSet; 43 | this.queries = ParseUtility.parseQueryStrings(request.queries, req); 44 | if(request.foreground_queries == null) { 45 | this.fgQueries = this.queries; 46 | } 47 | else { 48 | this.fgQueries = ParseUtility.parseQueryStrings(request.foreground_queries, req); 49 | } 50 | this.bgQueries = ParseUtility.parseQueryStrings(request.background_queries, req); 51 | this.queryDomain = req.getSearcher().getDocSet(queries); 52 | this.fgDomain= req.getSearcher().getDocSet(fgQueries); 53 | this.bgDomain = req.getSearcher().getDocSet(bgQueries); 54 | } 55 | 56 | // copy constructor 57 | public NodeContext(NodeContext parent, String filterQueryString) throws IOException 58 | { 59 | this.req = parent.req; 60 | this.request = parent.request; 61 | this.parameterSet = parent.parameterSet; 62 | this.queries = parent.queries; 63 | this.fgQueries = parent.fgQueries; 64 | this.bgQueries = parent.bgQueries; 65 | this.queryDomain = req.getSearcher().getDocSet(ParseUtility.parseQueryString(filterQueryString, req), parent.queryDomain); 66 | this.fgDomain= req.getSearcher().getDocSet(ParseUtility.parseQueryString(filterQueryString, req), parent.fgDomain); 67 | this.bgDomain= parent.bgDomain; 68 | } 69 | 70 | public NodeContext() {} 71 | 72 | 73 | } 74 | -------------------------------------------------------------------------------- /knowledge-graph/src/main/java/com/careerbuilder/search/relevancy/RecursionOp.java: -------------------------------------------------------------------------------- 1 | package com.careerbuilder.search.relevancy; 2 | 3 | import com.careerbuilder.search.relevancy.model.RequestNode; 4 | import com.careerbuilder.search.relevancy.model.ResponseNode; 5 | 6 | import java.io.IOException; 7 | 8 | public interface RecursionOp { 9 | 10 | ResponseNode [] transform(NodeContext nodeContext, RequestNode [] request, ResponseNode [] responses) throws IOException; 11 | 12 | } 13 | -------------------------------------------------------------------------------- /knowledge-graph/src/main/java/com/careerbuilder/search/relevancy/RequestTreeRecurser.java: -------------------------------------------------------------------------------- 1 | package com.careerbuilder.search.relevancy; 2 | 3 | import com.careerbuilder.search.relevancy.generation.NodeGenerator; 4 | import com.careerbuilder.search.relevancy.model.KnowledgeGraphRequest; 5 | import com.careerbuilder.search.relevancy.model.RequestNode; 6 | import com.careerbuilder.search.relevancy.model.ResponseNode; 7 | import com.careerbuilder.search.relevancy.model.ResponseValue; 8 | import com.careerbuilder.search.relevancy.normalization.NodeNormalizer; 9 | import com.careerbuilder.search.relevancy.scoring.NodeScorer; 10 | 11 | import java.io.IOException; 12 | 13 | public class RequestTreeRecurser { 14 | 15 | public static final int DEFAULT_REQUEST_LIMIT = 1; 16 | 17 | private KnowledgeGraphRequest request; 18 | private NodeContext baseContext; 19 | private RecursionOp normalizer; 20 | private RecursionOp generator; 21 | private RecursionOp scorer; 22 | 23 | public RequestTreeRecurser(NodeContext context) throws IOException { 24 | this(context, new NodeNormalizer(), new NodeGenerator(), new NodeScorer()); 25 | } 26 | 27 | public RequestTreeRecurser(NodeContext context, 28 | RecursionOp normalizer, 29 | RecursionOp generator, 30 | RecursionOp scorer) throws IOException { 31 | this.normalizer = normalizer; 32 | this.generator = generator; 33 | this.scorer = scorer; 34 | this.request = context.request; 35 | this.baseContext = context; 36 | } 37 | 38 | public ResponseNode[] score() throws IOException { 39 | ResponseNode[] responses = null; 40 | if(request.compare != null) { 41 | setDefaults(request.compare); 42 | if(baseContext.request.normalize) { 43 | normalizer.transform(baseContext, request.compare, null); 44 | } 45 | responses = generator.transform(baseContext, request.compare, null); 46 | responses = scorer.transform(baseContext, request.compare, responses); 47 | for(int i = 0; i < request.compare.length; ++i) { 48 | recurse(baseContext, responses[i], request.compare[i].compare); 49 | } 50 | } 51 | return responses; 52 | } 53 | 54 | private void recurse(NodeContext parentContext, ResponseNode parentResponse, RequestNode[] requests) throws IOException { 55 | if(requests != null) { 56 | setDefaults(requests); 57 | for (ResponseValue value : parentResponse.values) { 58 | String query = value.value == null || value.value.equals("") ? "*" : value.value.toLowerCase(); 59 | NodeContext context = new NodeContext(parentContext, parentResponse.type+":"+query); 60 | if(context.request.normalize) { 61 | normalizer.transform(context, requests, null); 62 | } 63 | ResponseNode [] responses = generator.transform(context, requests, null); 64 | value.compare = scorer.transform(context, requests, responses); 65 | for (int i = 0; i < requests.length; ++i) { 66 | recurse(context, value.compare[i], requests[i].compare); 67 | } 68 | } 69 | } 70 | } 71 | 72 | private void setDefaults(RequestNode [] requests) 73 | { 74 | for(RequestNode request: requests) { 75 | if (request.values == null || request.values.length == 0) { 76 | request.discover_values = true; 77 | } 78 | int limit = request.values == null || request.values.length == 0 ? DEFAULT_REQUEST_LIMIT : request.values.length; 79 | request.limit = request.limit == 0 ? limit : request.limit; 80 | } 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /knowledge-graph/src/main/java/com/careerbuilder/search/relevancy/RequestValidator.java: -------------------------------------------------------------------------------- 1 | package com.careerbuilder.search.relevancy; 2 | 3 | import com.careerbuilder.search.relevancy.model.KnowledgeGraphRequest; 4 | import com.careerbuilder.search.relevancy.model.RequestNode; 5 | import org.apache.solr.common.SolrException; 6 | import org.apache.solr.request.SolrQueryRequest; 7 | 8 | public class RequestValidator { 9 | 10 | private KnowledgeGraphRequest request; 11 | private SolrQueryRequest solrRequest; 12 | 13 | public RequestValidator(SolrQueryRequest solrRequest, KnowledgeGraphRequest request) 14 | { 15 | this.request = request; 16 | this.solrRequest= solrRequest; 17 | } 18 | 19 | public void validate() 20 | { 21 | if(request.queries == null) { 22 | throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "No queries supplied for generation / scoring"); 23 | } 24 | if(request.compare == null || request.compare.length == 0) { 25 | throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "Request contains no compare node or an empty compare node"); 26 | } 27 | for(int i = 0; i < request.compare.length; ++i) { 28 | recurse(request.compare[i]); 29 | } 30 | } 31 | 32 | private void recurse(RequestNode requestNode) 33 | { 34 | if(requestNode.type == null || requestNode.type.equals("")) { 35 | throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "A request node contains empty or null type."); 36 | } 37 | FieldChecker.checkField(solrRequest, requestNode.type, requestNode.type); 38 | 39 | if(requestNode.compare != null) { 40 | for (int i = 0; i < requestNode.compare.length; ++i){ 41 | recurse(requestNode.compare[i]); 42 | } 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /knowledge-graph/src/main/java/com/careerbuilder/search/relevancy/generation/FacetFieldAdapter.java: -------------------------------------------------------------------------------- 1 | package com.careerbuilder.search.relevancy.generation; 2 | 3 | import com.careerbuilder.search.relevancy.FieldChecker; 4 | import com.careerbuilder.search.relevancy.NodeContext; 5 | import org.apache.solr.common.util.SimpleOrderedMap; 6 | 7 | public class FacetFieldAdapter { 8 | 9 | NodeContext context; 10 | 11 | 12 | public String field; 13 | public String baseField; 14 | private String facetFieldExtension; 15 | private String globalFacetFieldExtension; 16 | private String facetFieldDelimiter; 17 | private String facetFieldValueDelimiter; 18 | private String facetFieldKey; 19 | 20 | @Deprecated 21 | public FacetFieldAdapter(String field) { 22 | this.field = field; 23 | this.baseField = field; 24 | } 25 | 26 | public FacetFieldAdapter(NodeContext context, String field) 27 | { 28 | this.context = context; 29 | this.facetFieldKey = context.parameterSet.invariants.get(field + ".key", ""); 30 | this.facetFieldExtension = context.parameterSet.invariants.get(field + ".facet-field", ""); 31 | this.globalFacetFieldExtension = context.parameterSet.invariants.get("facet-field-extension", ""); 32 | this.facetFieldDelimiter = context.parameterSet.invariants.get("facet-field-delimiter", "-"); 33 | this.facetFieldValueDelimiter = context.parameterSet.invariants.get("facet-field-value-delimiter", "^"); 34 | FieldChecker.checkField(context.req, field, field); 35 | this.baseField = field; 36 | this.field = buildField(field); 37 | } 38 | 39 | public SimpleOrderedMap getMapValue(SimpleOrderedMap bucket) { 40 | SimpleOrderedMap result = null; 41 | if(facetFieldExtension != null && !facetFieldExtension.equals("")) { 42 | result = new SimpleOrderedMap<>(); 43 | String value = (String) bucket.get("val"); 44 | String[] facetFieldKeys = facetFieldExtension.split(facetFieldDelimiter); 45 | String[] facetFieldValues = value.split("\\"+facetFieldValueDelimiter); 46 | for (int i = 0; i < facetFieldKeys.length && i < facetFieldValues.length; ++i) { 47 | if(!facetFieldValues.equals("")) { 48 | result.add(facetFieldKeys[i], facetFieldValues[i]); 49 | } 50 | } 51 | } 52 | return result; 53 | } 54 | 55 | public String getStringValue(SimpleOrderedMap bucket) 56 | { 57 | SimpleOrderedMap mapValues = getMapValue(bucket); 58 | if(mapValues == null) 59 | { 60 | return ((String) bucket.get("val")).replace(facetFieldValueDelimiter, " "); 61 | } 62 | return mapValues.get(this.facetFieldKey); 63 | } 64 | 65 | private String buildField(String field) { 66 | String facetField = extendField(field, facetFieldExtension); 67 | FieldChecker.checkField(context.req, field, facetField); 68 | return facetField; 69 | } 70 | 71 | private String extendField(String field, String extension) { 72 | StringBuilder facetField = new StringBuilder(); 73 | if(extension.equals("")) { 74 | facetField.append(field); 75 | } else { 76 | facetField.append(field).append(".").append(extension); 77 | } 78 | if(globalFacetFieldExtension != "") 79 | return facetField.append(".").append(globalFacetFieldExtension).toString(); 80 | else 81 | return facetField.toString(); 82 | } 83 | 84 | public boolean hasExtension() 85 | { 86 | return facetFieldExtension != null && !facetFieldExtension.equals(""); 87 | } 88 | 89 | 90 | } 91 | -------------------------------------------------------------------------------- /knowledge-graph/src/main/java/com/careerbuilder/search/relevancy/generation/NodeGenerator.java: -------------------------------------------------------------------------------- 1 | package com.careerbuilder.search.relevancy.generation; 2 | 3 | import com.careerbuilder.search.relevancy.model.RequestNode; 4 | import com.careerbuilder.search.relevancy.model.ResponseNode; 5 | import com.careerbuilder.search.relevancy.model.ResponseValue; 6 | import com.careerbuilder.search.relevancy.NodeContext; 7 | import com.careerbuilder.search.relevancy.RecursionOp; 8 | import com.careerbuilder.search.relevancy.waitable.AggregationWaitable; 9 | import com.careerbuilder.search.relevancy.waitable.Waitable; 10 | import com.careerbuilder.search.relevancy.threadpool.ThreadPool; 11 | import org.apache.lucene.search.MatchAllDocsQuery; 12 | import org.apache.lucene.search.Sort; 13 | import org.apache.solr.common.util.SimpleOrderedMap; 14 | 15 | import java.io.IOException; 16 | import java.util.List; 17 | import java.util.concurrent.Future; 18 | 19 | public class NodeGenerator implements RecursionOp { 20 | 21 | public ResponseNode [] transform(NodeContext context, RequestNode [] requests, ResponseNode [] responses) throws IOException { 22 | ResponseNode [] resps = new ResponseNode[requests.length]; 23 | AggregationWaitable[] runners = buildWaitables(context, requests); 24 | List> futures = ThreadPool.multiplex(runners); 25 | ThreadPool.demultiplex(futures); 26 | for(int i = 0; i < resps.length; ++i) { 27 | resps[i] = new ResponseNode(requests[i].type); 28 | mergeResponseValues(requests[i], resps[i], runners[i]); 29 | } 30 | return resps; 31 | } 32 | 33 | private void mergeResponseValues(RequestNode request, ResponseNode resp, AggregationWaitable runner) { 34 | int genLength = runner == null ? 0 : runner.buckets == null ? 0 :runner.buckets.size(); 35 | int requestValsLength = request.values == null ? 0 : request.values.length; 36 | resp.values = new ResponseValue[requestValsLength + genLength]; 37 | int k = addPassedInValues(request, resp); 38 | if(runner != null) { 39 | addGeneratedValues(resp, runner, k); 40 | } 41 | } 42 | 43 | private int addPassedInValues(RequestNode request, ResponseNode resp) { 44 | int k = 0; 45 | if(request.values != null) { 46 | for (; k < request.values.length; ++k) { 47 | resp.values[k] = new ResponseValue(request.values[k]); 48 | resp.values[k].normalizedValue = request.normalizedValues == null ? null : request.normalizedValues.get(k); 49 | } 50 | } 51 | return k; 52 | } 53 | 54 | private void addGeneratedValues(ResponseNode resp, AggregationWaitable runner, int k) { 55 | for (SimpleOrderedMap bucket: runner.buckets) { 56 | ResponseValue respValue = new ResponseValue(runner.adapter.getStringValue(bucket)); 57 | respValue.normalizedValue = runner.adapter.getMapValue(bucket); 58 | resp.values[k++] = respValue; 59 | } 60 | } 61 | 62 | private AggregationWaitable[] buildWaitables(NodeContext context, 63 | RequestNode [] requests) throws IOException { 64 | AggregationWaitable[] runners = new AggregationWaitable[requests.length]; 65 | for(int i = 0; i < requests.length; ++i) { 66 | if(requests[i].discover_values) { 67 | // populate required docListAndSet once and only if necessary 68 | if(context.queryDomainList == null) { 69 | context.queryDomainList = 70 | context.req.getSearcher().getDocListAndSet(new MatchAllDocsQuery(), 71 | context.queryDomain, Sort.INDEXORDER, 0, 0); 72 | } 73 | FacetFieldAdapter adapter = new FacetFieldAdapter(context, requests[i].type); 74 | runners[i] = new AggregationWaitable(context, 75 | adapter, 76 | adapter.field, 77 | 0, 78 | requests[i].limit); 79 | } 80 | } 81 | return runners; 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /knowledge-graph/src/main/java/com/careerbuilder/search/relevancy/model/Error.java: -------------------------------------------------------------------------------- 1 | package com.careerbuilder.search.relevancy.model; 2 | 3 | public class Error { 4 | public String msg; 5 | public int code; 6 | 7 | public Error(String msg, int code) 8 | { 9 | this.msg = msg; 10 | this.code = code; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /knowledge-graph/src/main/java/com/careerbuilder/search/relevancy/model/KnowledgeGraphRequest.java: -------------------------------------------------------------------------------- 1 | package com.careerbuilder.search.relevancy.model; 2 | 3 | public class KnowledgeGraphRequest 4 | { 5 | 6 | private static final int DEFAULT_MIN_POPULARITY = 1; 7 | 8 | public KnowledgeGraphRequest() { 9 | normalize = true; 10 | min_popularity = DEFAULT_MIN_POPULARITY; 11 | return_popularity = true; 12 | } 13 | 14 | public KnowledgeGraphRequest(RequestNode[] compare) 15 | { 16 | this.compare = compare; 17 | } 18 | 19 | public String [] queries; 20 | public String [] foreground_queries; 21 | public String [] background_queries; 22 | public double min_popularity; 23 | public boolean return_popularity; 24 | public boolean normalize; 25 | public RequestNode[] compare; 26 | } 27 | -------------------------------------------------------------------------------- /knowledge-graph/src/main/java/com/careerbuilder/search/relevancy/model/KnowledgeGraphResponse.java: -------------------------------------------------------------------------------- 1 | package com.careerbuilder.search.relevancy.model; 2 | 3 | public class KnowledgeGraphResponse 4 | { 5 | public ResponseNode [] data; 6 | public Error error; 7 | } 8 | -------------------------------------------------------------------------------- /knowledge-graph/src/main/java/com/careerbuilder/search/relevancy/model/ParameterSet.java: -------------------------------------------------------------------------------- 1 | package com.careerbuilder.search.relevancy.model; 2 | 3 | import org.apache.solr.common.params.SolrParams; 4 | 5 | public class ParameterSet { 6 | 7 | public ParameterSet(SolrParams params, SolrParams defaults, SolrParams invariants) 8 | { 9 | this.params = params; 10 | this.defaults = defaults; 11 | this.invariants = invariants; 12 | } 13 | public SolrParams params; 14 | public SolrParams defaults; 15 | public SolrParams invariants; 16 | } 17 | -------------------------------------------------------------------------------- /knowledge-graph/src/main/java/com/careerbuilder/search/relevancy/model/RequestNode.java: -------------------------------------------------------------------------------- 1 | package com.careerbuilder.search.relevancy.model; 2 | 3 | import org.apache.solr.common.util.SimpleOrderedMap; 4 | 5 | import java.util.List; 6 | 7 | public class RequestNode { 8 | public String type; 9 | public String [] values; 10 | public List> normalizedValues; 11 | public SortType sort; 12 | public int limit; 13 | public boolean discover_values; 14 | public RequestNode[] compare; 15 | 16 | public RequestNode() {} 17 | 18 | public RequestNode(RequestNode[] compare, 19 | String type) { 20 | this.type = type; 21 | this.compare = compare; 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /knowledge-graph/src/main/java/com/careerbuilder/search/relevancy/model/ResponseNode.java: -------------------------------------------------------------------------------- 1 | package com.careerbuilder.search.relevancy.model; 2 | 3 | public class ResponseNode { 4 | public String type; 5 | public ResponseValue[] values; 6 | 7 | public ResponseNode(){} 8 | 9 | public ResponseNode(String type) { 10 | this.type = type; 11 | } 12 | 13 | 14 | } 15 | -------------------------------------------------------------------------------- /knowledge-graph/src/main/java/com/careerbuilder/search/relevancy/model/ResponseValue.java: -------------------------------------------------------------------------------- 1 | package com.careerbuilder.search.relevancy.model; 2 | 3 | import com.careerbuilder.search.relevancy.utility.MapUtility; 4 | import org.apache.solr.common.util.SimpleOrderedMap; 5 | 6 | public class ResponseValue { 7 | public String value; 8 | public SimpleOrderedMap normalizedValue; 9 | public double relatedness; 10 | public double foreground_popularity; 11 | public double background_popularity; 12 | public double popularity; 13 | public ResponseNode [] compare; 14 | 15 | public ResponseValue(String value) { 16 | this.value = value; 17 | } 18 | 19 | public ResponseValue(ResponseValue other) 20 | { 21 | value = other.value; 22 | normalizedValue = other.normalizedValue; 23 | relatedness = other.relatedness; 24 | foreground_popularity = other.foreground_popularity; 25 | background_popularity = other.background_popularity; 26 | popularity = other.popularity; 27 | compare = other.compare; 28 | } 29 | 30 | @Override 31 | public boolean equals(Object other) 32 | { 33 | if(other instanceof ResponseValue) { 34 | ResponseValue cast = (ResponseValue)other; 35 | return value.equals(cast.value) && relatedness == cast.relatedness && foreground_popularity == cast.foreground_popularity 36 | && background_popularity == cast.background_popularity; 37 | } 38 | return false; 39 | } 40 | 41 | // nb: not transitive 42 | public boolean expandedEquals(ResponseValue other) 43 | { 44 | return this.valuesEqual(other) 45 | && foreground_popularity == other.foreground_popularity 46 | && background_popularity == other.background_popularity 47 | && popularity == other.popularity; 48 | } 49 | 50 | public boolean valuesEqual(ResponseValue other) { 51 | return this.value.equalsIgnoreCase(other.value) 52 | || MapUtility.mapContainsValue(this.value, other.normalizedValue) 53 | || MapUtility.mapContainsValue(other.value, this.normalizedValue) 54 | || MapUtility.mapsEqual(this.normalizedValue, other.normalizedValue); 55 | } 56 | 57 | public ResponseValue(String value, double foreground_popularity) 58 | { 59 | this(value); 60 | this.foreground_popularity = foreground_popularity; 61 | } 62 | 63 | } 64 | -------------------------------------------------------------------------------- /knowledge-graph/src/main/java/com/careerbuilder/search/relevancy/model/SortType.java: -------------------------------------------------------------------------------- 1 | package com.careerbuilder.search.relevancy.model; 2 | 3 | public enum SortType { 4 | relatedness, 5 | foreground_popularity, 6 | background_popularity, 7 | popularity, 8 | } 9 | -------------------------------------------------------------------------------- /knowledge-graph/src/main/java/com/careerbuilder/search/relevancy/normalization/NodeNormalizer.java: -------------------------------------------------------------------------------- 1 | package com.careerbuilder.search.relevancy.normalization; 2 | 3 | import com.careerbuilder.search.relevancy.generation.FacetFieldAdapter; 4 | import com.careerbuilder.search.relevancy.model.RequestNode; 5 | import com.careerbuilder.search.relevancy.model.ResponseNode; 6 | import com.careerbuilder.search.relevancy.NodeContext; 7 | import com.careerbuilder.search.relevancy.RecursionOp; 8 | import com.careerbuilder.search.relevancy.waitable.AggregationWaitable; 9 | import com.careerbuilder.search.relevancy.waitable.Waitable; 10 | import com.careerbuilder.search.relevancy.threadpool.ThreadPool; 11 | import com.careerbuilder.search.relevancy.utility.MapUtility; 12 | import org.apache.lucene.search.MatchAllDocsQuery; 13 | import org.apache.lucene.search.Sort; 14 | import org.apache.solr.common.util.SimpleOrderedMap; 15 | 16 | import java.io.IOException; 17 | import java.util.LinkedList; 18 | import java.util.List; 19 | import java.util.Map; 20 | import java.util.TreeMap; 21 | import java.util.concurrent.Future; 22 | 23 | public class NodeNormalizer implements RecursionOp { 24 | 25 | private static final int DEFAULT_NORM_LIMIT = 100; 26 | 27 | public ResponseNode [] transform(NodeContext context, RequestNode [] requests, ResponseNode [] responses) throws IOException { 28 | Map> runners = buildRunners(context, requests); 29 | List> futures = ThreadPool.multiplex(runners.values().stream() 30 | .flatMap(l->l.stream()).toArray(AggregationWaitable[]::new)); 31 | ThreadPool.demultiplex(futures); 32 | normalizeRequests(requests, runners); 33 | return null; 34 | } 35 | 36 | public void normalizeRequests(RequestNode[] requests, Map> runners) { 37 | for(int i = 0; i < requests.length; ++i) { 38 | normalizeSingleRequest(requests[i], runners.get(requests[i].type)); 39 | } 40 | } 41 | 42 | private void normalizeSingleRequest(RequestNode request, List runners) { 43 | if(runners.size() > 0 && request.values != null && runners.get(0).adapter.hasExtension()) 44 | { 45 | LinkedList normalizedStrings = new LinkedList<>(); 46 | LinkedList> normalizedMaps= new LinkedList<>(); 47 | for(AggregationWaitable runner : runners) 48 | { 49 | populateNorms(runner, request.values[runner.index], normalizedStrings, normalizedMaps); 50 | } 51 | request.normalizedValues = normalizedMaps; 52 | request.values = normalizedStrings.toArray(new String[normalizedStrings.size()]); 53 | } 54 | } 55 | 56 | private void populateNorms(AggregationWaitable runner, 57 | String requestValue, 58 | LinkedList normalizedStrings, 59 | LinkedList> normalizedMaps) { 60 | for(SimpleOrderedMap bucket : runner.buckets) 61 | { 62 | SimpleOrderedMap facetResult = runner.adapter.getMapValue(bucket); 63 | if(MapUtility.mapContainsValue(requestValue.toLowerCase(), facetResult)) 64 | { 65 | normalizedStrings.add(runner.adapter.getStringValue(bucket)); 66 | normalizedMaps.add(runner.adapter.getMapValue(bucket)); 67 | return; 68 | } 69 | } 70 | normalizedStrings.add(requestValue); 71 | normalizedMaps.add(null); 72 | } 73 | 74 | private Map> buildRunners(NodeContext context, RequestNode [] requests) throws IOException 75 | { 76 | Map> runners = new TreeMap<>(); 77 | for(int i = 0; i < requests.length; ++i) 78 | { 79 | runners.put(requests[i].type, buildWaitables(context, requests[i])); 80 | } 81 | return runners; 82 | } 83 | 84 | private List buildWaitables(NodeContext context, RequestNode request) throws IOException { 85 | List runners = new LinkedList<>(); 86 | FacetFieldAdapter adapter = new FacetFieldAdapter(context, request.type); 87 | if(request.values != null && adapter.hasExtension()) 88 | { 89 | for (int k = 0; k < request.values.length; ++k) 90 | { 91 | // load required docListAndSet once and only if necessary 92 | if (context.queryDomainList == null) 93 | { 94 | context.queryDomainList = 95 | context.req.getSearcher().getDocListAndSet(new MatchAllDocsQuery(), 96 | context.queryDomain, Sort.INDEXORDER, 0, 0); 97 | } 98 | String facetQuery = buildFacetQuery(adapter.baseField, request.values[k].toLowerCase()); 99 | runners.add(new AggregationWaitable(context, adapter, facetQuery, adapter.field, k, DEFAULT_NORM_LIMIT)); 100 | } 101 | } 102 | return runners; 103 | } 104 | 105 | private String buildFacetQuery(String field, String inputValue) { 106 | if(inputValue == null) 107 | return field + ":*"; 108 | return field + ":\"" + inputValue + "\""; 109 | } 110 | } 111 | -------------------------------------------------------------------------------- /knowledge-graph/src/main/java/com/careerbuilder/search/relevancy/responsewriter/KnowledgeGraphResponseWriter.java: -------------------------------------------------------------------------------- 1 | package com.careerbuilder.search.relevancy.responsewriter; 2 | 3 | import com.careerbuilder.search.relevancy.model.*; 4 | import com.careerbuilder.search.relevancy.model.Error; 5 | import com.google.gson.Gson; 6 | import com.google.gson.GsonBuilder; 7 | import org.apache.solr.common.util.NamedList; 8 | import org.apache.solr.request.SolrQueryRequest; 9 | import org.apache.solr.response.QueryResponseWriter; 10 | import org.apache.solr.response.SolrQueryResponse; 11 | 12 | import java.io.IOException; 13 | import java.io.Writer; 14 | 15 | public class KnowledgeGraphResponseWriter implements QueryResponseWriter{ 16 | 17 | public void init(NamedList args) 18 | { 19 | 20 | } 21 | public String getContentType(SolrQueryRequest request, SolrQueryResponse response) 22 | { 23 | return "application/json"; 24 | } 25 | 26 | public void write(Writer writer, SolrQueryRequest request, SolrQueryResponse response) throws IOException 27 | { 28 | Gson gson = new GsonBuilder().registerTypeAdapter(ResponseValue.class, new ResponseValueSerializer()).create(); 29 | Exception e = response.getException(); 30 | int status = (int)response.getResponseHeader().get("status"); 31 | KnowledgeGraphResponse model = (KnowledgeGraphResponse)response.getValues().get("relatednessResponse"); 32 | if(e != null) { 33 | if(model == null) { 34 | model = new KnowledgeGraphResponse(); 35 | } 36 | model.error = new Error(e.getMessage(), status); 37 | } 38 | writer.write(gson.toJson(model, KnowledgeGraphResponse.class)); 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /knowledge-graph/src/main/java/com/careerbuilder/search/relevancy/responsewriter/ResponseValueSerializer.java: -------------------------------------------------------------------------------- 1 | package com.careerbuilder.search.relevancy.responsewriter; 2 | 3 | import com.careerbuilder.search.relevancy.model.ResponseValue; 4 | import com.google.gson.JsonElement; 5 | import com.google.gson.JsonObject; 6 | import com.google.gson.JsonSerializationContext; 7 | import com.google.gson.JsonSerializer; 8 | 9 | import java.lang.reflect.Type; 10 | 11 | public class ResponseValueSerializer implements JsonSerializer { 12 | 13 | private final static String DEFAULT_VALUE_FIELD = "name"; 14 | 15 | public JsonElement serialize(ResponseValue src, Type type, JsonSerializationContext context) 16 | { 17 | JsonObject resp = new JsonObject(); 18 | if(src.normalizedValue == null) { 19 | resp.addProperty(DEFAULT_VALUE_FIELD, src.value); 20 | } 21 | else { 22 | src.normalizedValue.forEach((elem) -> resp.addProperty(elem.getKey(), elem.getValue())); 23 | } 24 | resp.addProperty("relatedness", src.relatedness); 25 | resp.addProperty("popularity", src.popularity); 26 | resp.addProperty("foreground_popularity", src.foreground_popularity); 27 | resp.addProperty("background_popularity", src.background_popularity); 28 | resp.add("compare", context.serialize(src.compare)); 29 | return resp; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /knowledge-graph/src/main/java/com/careerbuilder/search/relevancy/scoring/BackupScorer.java: -------------------------------------------------------------------------------- 1 | package com.careerbuilder.search.relevancy.scoring; 2 | 3 | import com.careerbuilder.search.relevancy.NodeContext; 4 | import com.careerbuilder.search.relevancy.model.ResponseNode; 5 | import com.careerbuilder.search.relevancy.waitable.QueryWaitable; 6 | 7 | import java.util.HashSet; 8 | import java.util.LinkedList; 9 | import java.util.List; 10 | import java.util.stream.Collectors; 11 | 12 | public class BackupScorer 13 | { 14 | public void runFallback(NodeContext context, 15 | ResponseNode response, 16 | List qRunners, 17 | String fallbackField) { 18 | List fgQueryWaitables = qRunners.stream().filter(q -> q.type == QueryWaitable.QueryType.FG).collect(Collectors.toList()); 19 | HashSet fallbackIndices = getFallbackIndices(fgQueryWaitables, context.request.min_popularity); 20 | QueryRunnerFactory factory = new QueryRunnerFactory(context, response, fallbackIndices); 21 | List fallbackRunners = new LinkedList<>(); 22 | fallbackRunners.addAll(factory.getQueryRunners(context.fgDomain, fallbackField, QueryWaitable.QueryType.FG)); 23 | fallbackRunners.addAll(factory.getQueryRunners(context.bgDomain, fallbackField, QueryWaitable.QueryType.BG)); 24 | if(context.request.return_popularity) 25 | { 26 | fallbackRunners.addAll(factory.getQueryRunners(context.queryDomain, fallbackField, QueryWaitable.QueryType.Q)); 27 | } 28 | NodeScorer.parallelQuery(fallbackRunners); 29 | replaceRunners(qRunners, fallbackRunners); 30 | } 31 | 32 | protected HashSet getFallbackIndices(List values, double minCount) 33 | { 34 | HashSet indices = new HashSet<>(); 35 | for(QueryWaitable runner : values) 36 | { 37 | if(runner.result < minCount || runner.result == 0) { 38 | indices.add(runner.index); 39 | } 40 | } 41 | return indices; 42 | } 43 | 44 | protected void replaceRunners(List target, List replacers) { 45 | target.removeAll(replacers); 46 | target.addAll(replacers); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /knowledge-graph/src/main/java/com/careerbuilder/search/relevancy/scoring/BinomialStrategy.java: -------------------------------------------------------------------------------- 1 | package com.careerbuilder.search.relevancy.scoring; 2 | 3 | public class BinomialStrategy 4 | { 5 | 6 | public static double score(int fgTotal, int bgTotal, double fgCount, double bgCount) { 7 | double bgProb = (bgCount / bgTotal); 8 | double num = fgCount - fgTotal * bgProb; 9 | double denom = Math.sqrt(fgTotal * bgProb * (1 - bgProb)); 10 | denom = (denom == 0) ? 1e-10 : denom; 11 | double z = num / denom; 12 | double result = 0.2*sigmoid(z, -80, 50) 13 | + 0.2*sigmoid(z, -30, 30) 14 | + 0.2*sigmoid(z, 0, 30) 15 | + 0.2*sigmoid(z, 30, 30) 16 | + 0.2*sigmoid(z, 80, 50); 17 | return Math.round(result * 1e5) / 1e5; 18 | } 19 | 20 | private static double sigmoid(double x, double offset, double scale) { 21 | return (x+offset) / (scale + Math.abs(x+offset)); 22 | } 23 | } 24 | 25 | -------------------------------------------------------------------------------- /knowledge-graph/src/main/java/com/careerbuilder/search/relevancy/scoring/NodeScorer.java: -------------------------------------------------------------------------------- 1 | package com.careerbuilder.search.relevancy.scoring; 2 | 3 | import com.careerbuilder.search.relevancy.model.RequestNode; 4 | import com.careerbuilder.search.relevancy.model.ResponseNode; 5 | import com.careerbuilder.search.relevancy.NodeContext; 6 | import com.careerbuilder.search.relevancy.RecursionOp; 7 | import com.careerbuilder.search.relevancy.model.ResponseValue; 8 | import com.careerbuilder.search.relevancy.waitable.QueryWaitable; 9 | import com.careerbuilder.search.relevancy.waitable.Waitable; 10 | import com.careerbuilder.search.relevancy.threadpool.ThreadPool; 11 | import com.careerbuilder.search.relevancy.utility.ResponseUtility; 12 | import org.apache.solr.common.SolrException; 13 | 14 | import java.util.LinkedList; 15 | import java.util.List; 16 | import java.util.concurrent.Future; 17 | 18 | public class NodeScorer implements RecursionOp { 19 | 20 | public ResponseNode[] transform(NodeContext context, RequestNode[] requests, ResponseNode[] responses) { 21 | for(int i = 0; i < responses.length; ++i) { 22 | QueryRunnerFactory factory = new QueryRunnerFactory(context, responses[i], null); 23 | 24 | List qRunners = new LinkedList<>(); 25 | qRunners.addAll(factory.getQueryRunners(context.fgDomain, 26 | responses[i].type, QueryWaitable.QueryType.FG)); 27 | qRunners.addAll(factory.getQueryRunners(context.bgDomain, 28 | responses[i].type, QueryWaitable.QueryType.BG)); 29 | if(context.request.return_popularity) 30 | qRunners.addAll(factory.getQueryRunners(context.queryDomain, responses[i].type, QueryWaitable.QueryType.Q)); 31 | 32 | parallelQuery(qRunners); 33 | 34 | String fallbackField = context.parameterSet.invariants.get(responses[i].type + ".fallback"); 35 | if(fallbackField != null) 36 | { 37 | new BackupScorer().runFallback(context, responses[i], qRunners, fallbackField); 38 | } 39 | addQueryResults(responses[i], qRunners); 40 | processResponse(context, responses[i], requests[i]); 41 | } 42 | return responses; 43 | } 44 | 45 | protected static void parallelQuery(List qRunners) 46 | { 47 | List> futures = new LinkedList<>(); 48 | futures.addAll(ThreadPool.multiplex(qRunners.toArray(new Waitable[0]))); 49 | ThreadPool.demultiplex(futures); 50 | } 51 | 52 | private void addQueryResults(ResponseNode response, List qRunners) { 53 | for(QueryWaitable queryWaitable : qRunners ) 54 | { 55 | if (queryWaitable != null) 56 | { 57 | setResultValue(response.values[queryWaitable.index], queryWaitable.result, queryWaitable.type); 58 | } 59 | } 60 | } 61 | 62 | private void setResultValue(ResponseValue toSet, double result, QueryWaitable.QueryType type) 63 | { 64 | switch(type) 65 | { 66 | case FG: 67 | toSet.foreground_popularity = result; 68 | break; 69 | case BG: 70 | toSet.background_popularity = result; 71 | break; 72 | case Q: 73 | toSet.popularity = result; 74 | break; 75 | default: 76 | throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "Unknown QueryType."); 77 | } 78 | } 79 | 80 | private void processResponse(NodeContext context, ResponseNode response, RequestNode request) 81 | { 82 | if(response.values != null && response.values.length > 0) { 83 | int fgTotal = context.fgDomain.size(); 84 | int bgTotal = context.bgDomain.size(); 85 | relatednessScore(response, fgTotal, bgTotal); 86 | ScoreNormalizer.normalize(context, response.values); 87 | response.values = ResponseUtility.filterAndSortValues(response.values, request, context.request); 88 | } 89 | } 90 | 91 | private void relatednessScore(ResponseNode response, int fgTotal, int bgTotal) { 92 | for (int k = 0; k < response.values.length; ++k) { 93 | response.values[k].relatedness = BinomialStrategy.score(fgTotal, 94 | bgTotal, response.values[k].foreground_popularity, response.values[k].background_popularity); 95 | } 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /knowledge-graph/src/main/java/com/careerbuilder/search/relevancy/scoring/QueryRunnerFactory.java: -------------------------------------------------------------------------------- 1 | package com.careerbuilder.search.relevancy.scoring; 2 | 3 | import com.careerbuilder.search.relevancy.model.ResponseNode; 4 | import com.careerbuilder.search.relevancy.NodeContext; 5 | import com.careerbuilder.search.relevancy.waitable.QueryWaitable; 6 | import com.careerbuilder.search.relevancy.utility.ParseUtility; 7 | import org.apache.lucene.search.Query; 8 | import org.apache.solr.search.DocSet; 9 | 10 | import java.util.HashSet; 11 | import java.util.LinkedList; 12 | import java.util.List; 13 | 14 | public class QueryRunnerFactory 15 | { 16 | private NodeContext context; 17 | private ResponseNode response; 18 | HashSet fallbackIndices; 19 | 20 | public QueryRunnerFactory(NodeContext context, ResponseNode response, HashSet fallbackIndices) 21 | { 22 | this.context = context; 23 | this.response = response; 24 | this.fallbackIndices = fallbackIndices; 25 | } 26 | 27 | protected List getQueryRunners(DocSet domain, String field, QueryWaitable.QueryType type) { 28 | List runners = new LinkedList<>(); 29 | if(fallbackIndices == null) 30 | { 31 | for (int k = 0; k < response.values.length; ++k) 32 | { 33 | runners.add(buildRunner(domain, type, 34 | field, response.values[k].value.toLowerCase().trim(), k)); 35 | } 36 | } 37 | else 38 | { 39 | for (Integer k : fallbackIndices) 40 | { 41 | runners.add(buildRunner(domain, type, 42 | field, response.values[k].value.toLowerCase().trim(), k)); 43 | } 44 | } 45 | return runners; 46 | } 47 | 48 | private QueryWaitable buildRunner(DocSet domain, QueryWaitable.QueryType type, String field, String value, int index) 49 | { 50 | Query query = ParseUtility.parseQueryString( 51 | field + ":\"" + value + "\"", 52 | context.req); 53 | return new QueryWaitable(context.req.getSearcher(), query, domain, type, index); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /knowledge-graph/src/main/java/com/careerbuilder/search/relevancy/scoring/ScoreNormalizer.java: -------------------------------------------------------------------------------- 1 | package com.careerbuilder.search.relevancy.scoring; 2 | 3 | import com.careerbuilder.search.relevancy.model.ResponseValue; 4 | import com.careerbuilder.search.relevancy.NodeContext; 5 | import org.apache.lucene.search.MatchAllDocsQuery; 6 | import org.apache.lucene.search.TotalHitCountCollector; 7 | 8 | import java.io.IOException; 9 | 10 | public class ScoreNormalizer { 11 | 12 | public static void normalize(NodeContext context, ResponseValue[] values) { 13 | int totalDocs = 1; 14 | try { 15 | totalDocs = getTotalDocs(context); 16 | } catch (IOException e) {} 17 | 18 | normalizeValues(totalDocs, values); 19 | } 20 | 21 | private static int getTotalDocs(NodeContext context) throws IOException { 22 | TotalHitCountCollector collector = new TotalHitCountCollector(); 23 | context.req.getSearcher().search(new MatchAllDocsQuery(), collector); 24 | return collector.getTotalHits(); 25 | } 26 | 27 | private static void normalizeValues(int totalDocs, ResponseValue [] values) { 28 | for(int i = 0; i < values.length; ++i) { 29 | values[i].popularity = normalizeFunc(totalDocs, values[i].popularity); 30 | values[i].foreground_popularity = normalizeFunc(totalDocs, values[i].foreground_popularity); 31 | values[i].background_popularity = normalizeFunc(totalDocs, values[i].background_popularity); 32 | } 33 | } 34 | 35 | private static double normalizeFunc(int total, double value) { 36 | return Math.round((value *1e6) / total); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /knowledge-graph/src/main/java/com/careerbuilder/search/relevancy/threadpool/ThreadPool.java: -------------------------------------------------------------------------------- 1 | package com.careerbuilder.search.relevancy.threadpool; 2 | 3 | import com.careerbuilder.search.relevancy.waitable.Waitable; 4 | import org.apache.solr.common.SolrException; 5 | 6 | import java.util.*; 7 | import java.util.concurrent.ExecutionException; 8 | import java.util.concurrent.ExecutorService; 9 | import java.util.concurrent.Executors; 10 | import java.util.concurrent.Future; 11 | 12 | public class ThreadPool 13 | { 14 | private final ExecutorService pool = Executors.newCachedThreadPool(); 15 | 16 | public static ThreadPool getInstance() 17 | { 18 | return ThreadPoolHolder.pool; 19 | } 20 | 21 | public static synchronized Future execute(Waitable w) { 22 | return getInstance().pool.submit(w); 23 | } 24 | 25 | public static List demultiplex(List> futures) 26 | { 27 | List result = new LinkedList(); 28 | try 29 | { 30 | for (Future future : futures) 31 | { 32 | Waitable w = future.get(); 33 | if(w.e != null) 34 | { 35 | throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, 36 | "Error executing thread. ", w.e); 37 | } 38 | result.add(w); 39 | } 40 | } 41 | catch (InterruptedException e) 42 | { 43 | throw new SolrException( 44 | SolrException.ErrorCode.SERVER_ERROR, "Parallel Operation interrupted", e); 45 | } 46 | catch (ExecutionException e) 47 | { 48 | throw new SolrException( 49 | SolrException.ErrorCode.SERVER_ERROR, "Execution exception. ", e); 50 | } 51 | return result; 52 | } 53 | 54 | public static List> multiplex(Waitable [] array) 55 | { 56 | LinkedList> futures = new LinkedList<>(); 57 | for(int i = 0; i < array.length; ++i) { 58 | if(array[i] != null) { 59 | futures.addLast(execute(array[i])); 60 | } 61 | } 62 | return futures; 63 | } 64 | } -------------------------------------------------------------------------------- /knowledge-graph/src/main/java/com/careerbuilder/search/relevancy/threadpool/ThreadPoolHolder.java: -------------------------------------------------------------------------------- 1 | package com.careerbuilder.search.relevancy.threadpool; 2 | 3 | public class ThreadPoolHolder 4 | { 5 | static ThreadPool pool = new ThreadPool(); 6 | } 7 | -------------------------------------------------------------------------------- /knowledge-graph/src/main/java/com/careerbuilder/search/relevancy/utility/MapUtility.java: -------------------------------------------------------------------------------- 1 | package com.careerbuilder.search.relevancy.utility; 2 | 3 | import org.apache.solr.common.util.SimpleOrderedMap; 4 | 5 | public class MapUtility { 6 | public static boolean mapContainsValue(String value, SimpleOrderedMap normValues) { 7 | if(normValues != null) { 8 | for(int i = 0; i < normValues.size(); ++i) { 9 | if(normValues.getVal(i).equalsIgnoreCase(value)) 10 | return true; 11 | } 12 | } 13 | return false; 14 | } 15 | 16 | public static boolean mapsEqual(SimpleOrderedMap map1, SimpleOrderedMap map2) { 17 | if(map1 != null && map2 != null) { 18 | if(map1.size() != map2.size()) { 19 | return false; 20 | } 21 | for (int i = 0; i < map1.size(); ++i) { 22 | if (!map1.getVal(i).equals(map2.getVal(i))) { 23 | return false; 24 | } 25 | } 26 | return true; 27 | } 28 | return false; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /knowledge-graph/src/main/java/com/careerbuilder/search/relevancy/utility/ParseUtility.java: -------------------------------------------------------------------------------- 1 | package com.careerbuilder.search.relevancy.utility; 2 | 3 | import org.apache.lucene.search.MatchAllDocsQuery; 4 | import org.apache.lucene.search.Query; 5 | import org.apache.solr.common.SolrException; 6 | import org.apache.solr.request.SolrQueryRequest; 7 | import org.apache.solr.search.QParser; 8 | import org.apache.solr.search.SyntaxError; 9 | 10 | import java.util.LinkedList; 11 | import java.util.List; 12 | 13 | public class ParseUtility 14 | { 15 | public static List parseQueryStrings(String [] qStrings, SolrQueryRequest req) { 16 | if(qStrings != null) { 17 | LinkedList queryList = new LinkedList(); 18 | for (String qString : qStrings) { 19 | queryList.add(parseQueryString(qString, req)); 20 | } 21 | return queryList; 22 | } 23 | List deflt = new LinkedList<>(); 24 | deflt.add(new MatchAllDocsQuery()); 25 | return deflt; 26 | } 27 | 28 | public static Query parseQueryString(String qString, SolrQueryRequest req) { 29 | try { 30 | QParser parser = QParser.getParser(qString, req.getParams().get("defType"), req); 31 | return parser.getQuery(); 32 | } catch (SyntaxError e) { 33 | throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, 34 | "Syntax error in query: " + qString + "."); 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /knowledge-graph/src/main/java/com/careerbuilder/search/relevancy/utility/ResponseUtility.java: -------------------------------------------------------------------------------- 1 | package com.careerbuilder.search.relevancy.utility; 2 | 3 | import com.careerbuilder.search.relevancy.model.*; 4 | 5 | import java.util.*; 6 | import java.util.stream.Collectors; 7 | 8 | public class ResponseUtility { 9 | 10 | // keeps all passed in values, up to request.limit 11 | // keeps as many generated values as possible up to request.limit 12 | public static ResponseValue[] filterAndSortValues(ResponseValue [] responses, RequestNode node, KnowledgeGraphRequest request) { 13 | List scoredValues = new ArrayList<>(Arrays.asList(responses)); 14 | SortUtility.sortResponseValues(scoredValues, node.sort); 15 | 16 | 17 | if (request.return_popularity) 18 | { 19 | scoredValues = thresholdMinPop(scoredValues, request.min_popularity); 20 | } 21 | else 22 | { 23 | scoredValues = thresholdMinFGBGPop(scoredValues, request.min_popularity); 24 | } 25 | distinct(scoredValues); 26 | if(node.discover_values && scoredValues.size() > 0) { 27 | List requestValues = distinct(node.values); 28 | int limit = Math.min(scoredValues.size(), node.limit); 29 | scoredValues = filterMergeResults(scoredValues, requestValues, limit, node.sort); 30 | } 31 | return scoredValues.toArray(new ResponseValue[scoredValues.size()]); 32 | } 33 | 34 | protected static List thresholdMinPop(List values, double threshold) 35 | { 36 | values = values.stream().filter((ResponseValue r) -> 37 | (r.popularity >= threshold)).collect(Collectors.toList()); 38 | return thresholdMinFGBGPop(values, threshold); 39 | } 40 | 41 | protected static List thresholdMinFGBGPop(List values, double threshold) { 42 | return values.stream().filter((ResponseValue r) -> (r.background_popularity >= threshold 43 | && r.foreground_popularity >= threshold)).collect(Collectors.toList()); 44 | } 45 | 46 | protected static List distinct(String [] requestValues ) 47 | { 48 | return new LinkedList<>( 49 | (Arrays.stream(requestValues == null ? new String[0] : requestValues).collect( 50 | Collectors.toMap(String::toLowerCase, s -> s, (first, second) -> first)) 51 | .values())); 52 | } 53 | 54 | public static void distinct(List responseValues) 55 | { 56 | for(int i = 1; i < responseValues.size();) { 57 | if(responseValues.get(i).expandedEquals(responseValues.get(i-1))) { 58 | responseValues.remove(i-1); 59 | } 60 | else { ++i; } 61 | } 62 | } 63 | 64 | // move any keep values (request values) beyond the request limit to just within the request limit, replacing generated values 65 | public static List filterMergeResults(List results, 66 | List requestValues, int limit, SortType sort) 67 | { 68 | List keepSet = requestValues == null ? new LinkedList<>() : requestValues; 69 | if (keepSet.size() > results.size()) 70 | throw new IllegalArgumentException("The keep set is larger than the results set."); 71 | 72 | List keepList= new LinkedList<>(); 73 | List disposableList = new LinkedList<>(); 74 | for (ResponseValue r : results) 75 | { 76 | if (keepSet.stream().anyMatch(s -> r.valuesEqual(new ResponseValue(s)))) 77 | keepList.add(r); 78 | else 79 | disposableList.add(r); 80 | } 81 | 82 | if (keepList.size() < limit) 83 | { 84 | int numResultsToAdd = Math.min(limit - keepList.size(), disposableList.size()); 85 | keepList.addAll(disposableList.subList(0, numResultsToAdd)); 86 | } 87 | SortUtility.sortResponseValues(keepList, sort); 88 | return keepList; 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /knowledge-graph/src/main/java/com/careerbuilder/search/relevancy/utility/SortUtility.java: -------------------------------------------------------------------------------- 1 | package com.careerbuilder.search.relevancy.utility; 2 | 3 | import com.careerbuilder.search.relevancy.model.ResponseValue; 4 | import com.careerbuilder.search.relevancy.model.SortType; 5 | 6 | import java.util.Collections; 7 | import java.util.Comparator; 8 | import java.util.List; 9 | 10 | public class SortUtility 11 | { 12 | public static void sortResponseValues(List responseValues, SortType sortedBy) 13 | { 14 | 15 | if(sortedBy == null) 16 | sortedBy = SortType.relatedness; 17 | switch(sortedBy) { 18 | case foreground_popularity: 19 | sortByFG(responseValues); 20 | break; 21 | case popularity: 22 | sortByPopularity(responseValues); 23 | break; 24 | case background_popularity: 25 | sortByBG(responseValues); 26 | break; 27 | case relatedness: 28 | sortByRelatedness(responseValues); 29 | break; 30 | } 31 | } 32 | 33 | private static void sortByRelatedness(List values) 34 | { 35 | Collections.sort(values, Comparator.comparing((ResponseValue val) -> -1 * val.relatedness).thenComparing((ResponseValue val) -> val.value.toLowerCase())); 36 | } 37 | 38 | private static void sortByFG(List values) 39 | { 40 | Collections.sort(values, Comparator.comparing((ResponseValue val) -> -1 * val.foreground_popularity).thenComparing((ResponseValue val) -> val.value.toLowerCase())); 41 | } 42 | 43 | private static void sortByBG(List values) 44 | { 45 | Collections.sort(values, Comparator.comparing((ResponseValue val) -> -1 * val.background_popularity).thenComparing((ResponseValue val) -> val.value.toLowerCase())); 46 | } 47 | 48 | private static void sortByPopularity(List values) 49 | { 50 | Collections.sort(values, Comparator.comparing((ResponseValue val) -> -1 * val.popularity).thenComparing((ResponseValue val) -> val.value.toLowerCase())); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /knowledge-graph/src/main/java/com/careerbuilder/search/relevancy/waitable/AggregationWaitable.java: -------------------------------------------------------------------------------- 1 | package com.careerbuilder.search.relevancy.waitable; 2 | 3 | import com.careerbuilder.search.relevancy.NodeContext; 4 | import com.careerbuilder.search.relevancy.generation.FacetFieldAdapter; 5 | import org.apache.solr.common.params.FacetParams; 6 | import org.apache.solr.common.params.MapSolrParams; 7 | import org.apache.solr.common.params.SolrParams; 8 | import org.apache.solr.common.util.SimpleOrderedMap; 9 | import org.apache.solr.handler.component.ResponseBuilder; 10 | import org.apache.solr.request.LocalSolrQueryRequest; 11 | import org.apache.solr.request.SolrQueryRequest; 12 | import org.apache.solr.response.SolrQueryResponse; 13 | import org.apache.solr.search.facet.FacetModule; 14 | 15 | import java.io.IOException; 16 | import java.util.*; 17 | 18 | public class AggregationWaitable extends Waitable{ 19 | 20 | private int limit; 21 | private String field; 22 | public FacetFieldAdapter adapter; 23 | public List> buckets; 24 | public final int index; 25 | public String facetQuery; 26 | final NodeContext context; 27 | public static final String FIELD_FACET_NAME = "fieldFacet"; 28 | public static final String QUERY_FACET_NAME = "queryFacet"; 29 | 30 | public AggregationWaitable(NodeContext context, FacetFieldAdapter adapter, String facetQuery, String field, int index, int limit) { 31 | this(context, adapter, field, index, limit); 32 | this.facetQuery = facetQuery; 33 | } 34 | 35 | public AggregationWaitable(NodeContext context, FacetFieldAdapter adapter, String field, int index, int limit) { 36 | this.context = context; 37 | this.field = field; 38 | this.limit = limit; 39 | this.adapter = adapter; 40 | this.index = index; 41 | } 42 | 43 | public Waitable call() 44 | { 45 | try { 46 | aggregate(); 47 | } catch (Exception e) { this.e = e; } 48 | return this; 49 | } 50 | 51 | public void aggregate() throws IOException { 52 | FacetModule mod = new FacetModule(); 53 | SolrQueryResponse resp = new SolrQueryResponse(); 54 | ResponseBuilder rb = getResponseBuilder(resp); 55 | mod.prepare(rb); 56 | mod.process(rb); 57 | parseResponse(resp); 58 | } 59 | 60 | private ResponseBuilder getResponseBuilder(SolrQueryResponse resp) throws IOException { 61 | SolrQueryRequest req = new LocalSolrQueryRequest(context.req.getCore(), buildFacetParams()); 62 | req.setJSON(buildFacetJson()); 63 | ResponseBuilder rb = new ResponseBuilder(req, resp, null); 64 | rb.setResults(context.queryDomainList); 65 | return rb; 66 | } 67 | 68 | // this is kind of awkward, but necessary since JSON faceting is protected in Solr, 69 | // (we can only send object requests). 70 | private void parseResponse(SolrQueryResponse resp) { 71 | SimpleOrderedMap facet = (SimpleOrderedMap) 72 | ((SimpleOrderedMap)((SimpleOrderedMap) resp.getValues()).get("facets")).get(QUERY_FACET_NAME); 73 | if(facet != null) { 74 | SimpleOrderedMap innerFacet = (SimpleOrderedMap)facet.get(FIELD_FACET_NAME); 75 | if(innerFacet != null) 76 | { 77 | buckets = (List>)innerFacet.get("buckets"); 78 | } else { 79 | buckets = new LinkedList<>(); 80 | } 81 | } else { 82 | buckets = new LinkedList<>(); 83 | } 84 | } 85 | 86 | // see above 87 | public Map buildFacetJson() 88 | { 89 | int limit = 5*Math.max(this.limit, 25); 90 | LinkedHashMap wrapper = new LinkedHashMap<>(); 91 | LinkedHashMap queryFacetName = new LinkedHashMap<>(); 92 | LinkedHashMap queryFacetWrapper= new LinkedHashMap<>(); 93 | LinkedHashMap queryFacet= new LinkedHashMap<>(); 94 | LinkedHashMap fieldFacetName = new LinkedHashMap<>(); 95 | LinkedHashMap fieldFacetWrapper= new LinkedHashMap<>(); 96 | LinkedHashMap fieldFacet= new LinkedHashMap<>(); 97 | fieldFacet.put("type", "field"); 98 | fieldFacet.put("field", field); 99 | fieldFacet.put("limit", limit); 100 | fieldFacetWrapper.put("field", fieldFacet); 101 | fieldFacetName.put(FIELD_FACET_NAME, fieldFacetWrapper); 102 | queryFacet.put("facet", fieldFacetName); 103 | queryFacet.put("q", facetQuery); 104 | queryFacetWrapper.put("query", queryFacet); 105 | queryFacetName.put(QUERY_FACET_NAME, queryFacetWrapper); 106 | wrapper.put("facet", queryFacetName); 107 | return wrapper; 108 | } 109 | 110 | // see above 111 | public SolrParams buildFacetParams() 112 | { 113 | LinkedHashMap paramMap = new LinkedHashMap<>(); 114 | paramMap.put("facet.version", "1"); 115 | paramMap.put("wt", "json"); 116 | paramMap.put(FacetParams.FACET, "true"); 117 | return new MapSolrParams(paramMap); 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /knowledge-graph/src/main/java/com/careerbuilder/search/relevancy/waitable/QueryWaitable.java: -------------------------------------------------------------------------------- 1 | package com.careerbuilder.search.relevancy.waitable; 2 | 3 | import org.apache.lucene.search.Query; 4 | import org.apache.solr.search.DocSet; 5 | import org.apache.solr.search.SolrIndexSearcher; 6 | 7 | public class QueryWaitable extends Waitable { 8 | 9 | public enum QueryType {Q, FG, BG}; 10 | public QueryType type; 11 | public int result = 0; 12 | public final int index; 13 | 14 | protected Query query; 15 | SolrIndexSearcher searcher; 16 | DocSet filter; 17 | Exception e; 18 | 19 | public QueryWaitable(SolrIndexSearcher searcher, 20 | Query query, DocSet filter, 21 | QueryType type, 22 | int index) { 23 | this.query = query; 24 | this.searcher = searcher; 25 | this.filter = filter; 26 | this.type = type; 27 | this.index = index; 28 | } 29 | 30 | public Waitable call() { 31 | try { 32 | result = searcher.numDocs(query, filter); 33 | } catch (Exception e) {this.e = e; } 34 | return this; 35 | } 36 | 37 | public @Override boolean equals(Object other) 38 | { 39 | if(other instanceof QueryWaitable) 40 | { 41 | QueryWaitable instance = (QueryWaitable)other; 42 | return this.index == instance.index && this.type == instance.type; 43 | } 44 | return false; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /knowledge-graph/src/main/java/com/careerbuilder/search/relevancy/waitable/Waitable.java: -------------------------------------------------------------------------------- 1 | package com.careerbuilder.search.relevancy.waitable; 2 | 3 | import org.apache.commons.lang.NotImplementedException; 4 | 5 | import java.util.concurrent.Callable; 6 | 7 | public abstract class Waitable implements Callable{ 8 | public Exception e = null; 9 | 10 | public Waitable call() 11 | { 12 | e = new NotImplementedException(); 13 | throw new NotImplementedException(); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /knowledge-graph/src/test/java/com/careerbuilder/search/relevancy/Model/ResponseNodeTest.java: -------------------------------------------------------------------------------- 1 | package com.careerbuilder.search.relevancy.model; 2 | 3 | import com.careerbuilder.search.relevancy.utility.SortUtility; 4 | import org.junit.Before; 5 | import org.junit.Test; 6 | 7 | import java.util.Arrays; 8 | import java.util.List; 9 | 10 | import static junit.framework.TestCase.assertEquals; 11 | 12 | public class ResponseNodeTest { 13 | 14 | private ResponseNode node; 15 | private List values; 16 | 17 | @Before 18 | public void init() 19 | { 20 | node = new ResponseNode(); 21 | ResponseValue v1 = new ResponseValue("v1", 0.75); 22 | v1.relatedness = 0.75; 23 | v1.background_popularity = 0.75; 24 | v1.foreground_popularity = 0.75; 25 | v1.popularity = 0.75; 26 | ResponseValue v2 = new ResponseValue("v2", 0.5); 27 | v2.relatedness = 0.5; 28 | v2.background_popularity = 0.5; 29 | v2.foreground_popularity = 0.5; 30 | v2.popularity = 0.5; 31 | ResponseValue v3 = new ResponseValue("v3", 0.25); 32 | v3.relatedness = 0.25; 33 | v3.background_popularity = 0.25; 34 | v3.foreground_popularity = 0.25; 35 | v3.popularity = 0.25; 36 | values = Arrays.asList(new ResponseValue[]{v3, v2, v1}); 37 | } 38 | @Test 39 | public void testSortByFGPop() 40 | { 41 | SortUtility.sortResponseValues(values, SortType.foreground_popularity); 42 | assertEquals(0.75, values.get(0).foreground_popularity); 43 | assertEquals(0.5, values.get(1).foreground_popularity); 44 | assertEquals(0.25, values.get(2).foreground_popularity); 45 | } 46 | @Test 47 | public void testSortByRelatedness() 48 | { 49 | SortUtility.sortResponseValues(values, SortType.relatedness); 50 | assertEquals(0.75, values.get(0).relatedness); 51 | assertEquals(0.5, values.get(1).relatedness); 52 | assertEquals(0.25, values.get(2).relatedness); 53 | } 54 | @Test 55 | public void testSortByBGPop() 56 | { 57 | SortUtility.sortResponseValues(values, SortType.background_popularity); 58 | assertEquals(0.75, values.get(0).background_popularity); 59 | assertEquals(0.5, values.get(1).background_popularity); 60 | assertEquals(0.25, values.get(2).background_popularity); 61 | } 62 | 63 | @Test 64 | public void testSortByPopularity() 65 | { 66 | SortUtility.sortResponseValues(values, SortType.popularity); 67 | assertEquals(0.75, values.get(0).popularity); 68 | assertEquals(0.5, values.get(1).popularity); 69 | assertEquals(0.25, values.get(2).popularity); 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /knowledge-graph/src/test/java/com/careerbuilder/search/relevancy/Model/ResponseValueTest.java: -------------------------------------------------------------------------------- 1 | package com.careerbuilder.search.relevancy.model; 2 | 3 | import mockit.integration.junit4.JMockit; 4 | import org.apache.solr.common.util.SimpleOrderedMap; 5 | import org.junit.Assert; 6 | import org.junit.Test; 7 | import org.junit.runner.RunWith; 8 | 9 | @RunWith(JMockit.class) 10 | public class ResponseValueTest { 11 | 12 | @Test 13 | public void extendedEquals_equals() 14 | { 15 | ResponseValue r1 = new ResponseValue("test1", 1.0); 16 | ResponseValue r2 = new ResponseValue("12 test1", 1.0); 17 | 18 | r2.normalizedValue = new SimpleOrderedMap(); 19 | r2.normalizedValue.add("testkey1", "12"); 20 | r2.normalizedValue.add("testkey2", "test1"); 21 | 22 | Assert.assertTrue(r1.expandedEquals(r2)); 23 | Assert.assertTrue(r2.expandedEquals(r1)); 24 | } 25 | 26 | @Test 27 | public void extendedEquals_magnitudeDifferent() 28 | { 29 | ResponseValue r1 = new ResponseValue("test1", 1.0); 30 | ResponseValue r2 = new ResponseValue("12 test1", 1.1); 31 | 32 | r2.normalizedValue = new SimpleOrderedMap(); 33 | r2.normalizedValue.add("testkey1", "12"); 34 | r2.normalizedValue.add("testkey2", "test1"); 35 | 36 | Assert.assertTrue(!r1.expandedEquals(r2)); 37 | Assert.assertTrue(!r2.expandedEquals(r1)); 38 | } 39 | 40 | @Test 41 | public void valuesEqual_equal() 42 | { 43 | ResponseValue r1 = new ResponseValue("test1", 1.0); 44 | ResponseValue r2 = new ResponseValue("12 test1", 1.0); 45 | 46 | r2.normalizedValue = new SimpleOrderedMap<>(); 47 | r2.normalizedValue.add("testkey1", "12"); 48 | r2.normalizedValue.add("testkey2", "test1"); 49 | 50 | Assert.assertTrue(r1.valuesEqual(r2)); 51 | Assert.assertTrue(r2.valuesEqual(r1)); 52 | } 53 | 54 | @Test 55 | public void valuesEqual_equalUID() 56 | { 57 | ResponseValue r1 = new ResponseValue("12 test1", 1.0); 58 | ResponseValue r2 = new ResponseValue("12 test1", 1.0); 59 | 60 | r2.normalizedValue = new SimpleOrderedMap<>(); 61 | r2.normalizedValue.add("testkey1", "12"); 62 | r2.normalizedValue.add("testkey2", "test1"); 63 | 64 | Assert.assertTrue(r1.valuesEqual(r2)); 65 | Assert.assertTrue(r2.valuesEqual(r1)); 66 | } 67 | 68 | 69 | @Test 70 | public void valuesEqual_notEqual() 71 | { 72 | ResponseValue r1 = new ResponseValue("13.1 test1", 1.0); 73 | ResponseValue r2 = new ResponseValue("12 test1", 1.0); 74 | 75 | r2.normalizedValue = new SimpleOrderedMap<>(); 76 | r2.normalizedValue.add("testkey1", "12"); 77 | r2.normalizedValue.add("testkey2", "test1"); 78 | 79 | Assert.assertTrue(!r1.valuesEqual(r2)); 80 | Assert.assertTrue(!r2.valuesEqual(r1)); 81 | } 82 | 83 | } 84 | -------------------------------------------------------------------------------- /knowledge-graph/src/test/java/com/careerbuilder/search/relevancy/RequestTreeRecurserTest.java: -------------------------------------------------------------------------------- 1 | package com.careerbuilder.search.relevancy; 2 | 3 | import com.careerbuilder.search.relevancy.model.KnowledgeGraphRequest; 4 | import com.careerbuilder.search.relevancy.model.RequestNode; 5 | import com.careerbuilder.search.relevancy.model.ResponseNode; 6 | import com.careerbuilder.search.relevancy.model.ResponseValue; 7 | import com.careerbuilder.search.relevancy.normalization.NodeNormalizer; 8 | import com.careerbuilder.search.relevancy.scoring.NodeScorer; 9 | import com.careerbuilder.search.relevancy.generation.NodeGenerator; 10 | import com.careerbuilder.search.relevancy.utility.ParseUtility; 11 | import mockit.*; 12 | import mockit.integration.junit4.JMockit; 13 | import org.apache.lucene.search.MatchAllDocsQuery; 14 | import org.apache.lucene.search.Query; 15 | import org.apache.solr.request.SolrQueryRequest; 16 | import org.apache.solr.search.DocSet; 17 | import org.apache.solr.search.SolrIndexSearcher; 18 | import org.junit.Assert; 19 | import org.junit.Before; 20 | import org.junit.Test; 21 | import org.junit.runner.RunWith; 22 | 23 | import java.io.IOException; 24 | 25 | @RunWith(JMockit.class) 26 | public class RequestTreeRecurserTest { 27 | 28 | @Mocked 29 | SolrQueryRequest solrRequest; 30 | @Mocked 31 | SolrIndexSearcher searcher; 32 | 33 | @Before 34 | public void init() throws IOException 35 | { 36 | new MockUp() 37 | { 38 | @Mock 39 | public ResponseNode [] transform(NodeContext context, RequestNode [] requests, ResponseNode [] responses) 40 | { 41 | responses = new ResponseNode[requests.length]; 42 | for(int i = 0; i < requests.length; ++i) { 43 | ResponseNode response = new ResponseNode(requests[i].type); 44 | response.values = new ResponseValue[2]; 45 | response.values[0] = new ResponseValue("0"); 46 | response.values[1] = new ResponseValue("1"); 47 | responses[i] = response; 48 | } 49 | return responses; 50 | } 51 | }; 52 | 53 | new MockUp() 54 | { 55 | @Mock 56 | public ResponseNode [] transform(NodeContext context, RequestNode [] requests, ResponseNode [] responses) 57 | { 58 | return null; 59 | } 60 | }; 61 | 62 | new MockUp() 63 | { 64 | @Mock 65 | public ResponseNode [] transform(NodeContext context, RequestNode [] requests, ResponseNode [] responses) 66 | { 67 | return null; 68 | } 69 | }; 70 | 71 | 72 | 73 | new NonStrictExpectations() {{ 74 | solrRequest.getSearcher(); returns(searcher); 75 | }}; 76 | 77 | new NonStrictExpectations() {{ 78 | try { 79 | searcher.getDocSet((Query) any, (DocSet) any); 80 | returns(null); 81 | } catch (Exception e) {} 82 | }}; 83 | 84 | 85 | 86 | new NodeContext(); 87 | } 88 | 89 | @Test 90 | public void recurseComparables_Null() throws IOException { 91 | 92 | KnowledgeGraphRequest request = new KnowledgeGraphRequest(); 93 | NodeContext context = new NodeContext(request, solrRequest, null); 94 | RequestTreeRecurser target = new RequestTreeRecurser(context); 95 | ResponseNode[] actual = target.score(); 96 | 97 | Assert.assertArrayEquals(null, actual); 98 | } 99 | 100 | 101 | @Test 102 | public void recurseComparables_One() throws IOException { 103 | 104 | KnowledgeGraphRequest request = new KnowledgeGraphRequest( 105 | new RequestNode[1]); 106 | request.compare[0] = new RequestNode(null, "testType"); 107 | ResponseNode[] expected = new ResponseNode[1]; 108 | expected[0] = new ResponseNode("testType"); 109 | setTwoValues(expected[0]); 110 | NodeContext context = new NodeContext(request, solrRequest, null); 111 | RequestTreeRecurser target = new RequestTreeRecurser(context); 112 | 113 | ResponseNode[] actual = target.score(); 114 | 115 | checkComparableTree(expected, actual); 116 | } 117 | 118 | @Test 119 | public void recurseComparables_TwoTrunkTree() throws IOException { 120 | new MockUp() { 121 | @Mock 122 | private Query parseQueryString(String qString, SolrQueryRequest req) 123 | { 124 | return new MatchAllDocsQuery(); 125 | } 126 | }; 127 | 128 | KnowledgeGraphRequest request = new KnowledgeGraphRequest( 129 | new RequestNode[2]); 130 | request.normalize=true; 131 | request.compare[0] = new RequestNode(null, "testType0"); 132 | request.compare[1] = new RequestNode(null, "testType1"); 133 | request.compare[0].compare = new RequestNode[2]; 134 | request.compare[0].compare[0] = new RequestNode(null, "testType00"); 135 | request.compare[0].compare[1] = new RequestNode(null, "testType01"); 136 | ResponseNode[] expected = new ResponseNode[2]; 137 | expected[0] = new ResponseNode("testType0"); 138 | setTwoValues(expected[0]); 139 | setTwoCompares(expected[0].values[0]); 140 | setTwoCompares(expected[0].values[1]); 141 | setTwoValues(expected[0].values[0].compare[0]); 142 | setTwoValues(expected[0].values[0].compare[1]); 143 | setTwoValues(expected[0].values[1].compare[0]); 144 | setTwoValues(expected[0].values[1].compare[1]); 145 | expected[1] = new ResponseNode("testType1"); 146 | setTwoValues(expected[1]); 147 | NodeContext context = new NodeContext(request, solrRequest, null); 148 | RequestTreeRecurser target = new RequestTreeRecurser(context); 149 | 150 | ResponseNode[] actual = target.score(); 151 | 152 | checkComparableTree(expected, actual); 153 | } 154 | 155 | private void setTwoCompares(ResponseValue value) { 156 | value.compare = new ResponseNode[2]; 157 | value.compare[0] = new ResponseNode("testType00"); 158 | value.compare[1] = new ResponseNode("testType01"); 159 | } 160 | 161 | private void setTwoValues(ResponseNode expected) { 162 | expected.values = new ResponseValue[2]; 163 | expected.values[0] = new ResponseValue("0"); 164 | expected.values[1] = new ResponseValue("1"); 165 | } 166 | 167 | private void checkComparableTree(ResponseNode[] expected, ResponseNode[] actual) 168 | { 169 | if(actual!= null) { 170 | for(int i = 0; i < actual.length; ++i) { 171 | Assert.assertTrue(expected[i].type.compareTo(actual[i].type) == 0); 172 | for(int k = 0; k < actual[i].values.length; ++k) { 173 | Assert.assertTrue(expected[i].values[k].value.compareTo(actual[i].values[k].value) == 0); 174 | checkComparableTree(expected[i].values[k].compare, actual[i].values[k].compare); 175 | } 176 | } 177 | } 178 | } 179 | 180 | } 181 | -------------------------------------------------------------------------------- /knowledge-graph/src/test/java/com/careerbuilder/search/relevancy/RequestValidatorTest.java: -------------------------------------------------------------------------------- 1 | package com.careerbuilder.search.relevancy; 2 | 3 | import com.careerbuilder.search.relevancy.model.KnowledgeGraphRequest; 4 | import com.careerbuilder.search.relevancy.model.RequestNode; 5 | import com.careerbuilder.search.relevancy.model.ResponseNode; 6 | import com.careerbuilder.search.relevancy.utility.ParseUtility; 7 | import mockit.Mock; 8 | import mockit.MockUp; 9 | import mockit.Mocked; 10 | import mockit.NonStrictExpectations; 11 | import mockit.integration.junit4.JMockit; 12 | import org.apache.lucene.search.MatchAllDocsQuery; 13 | import org.apache.lucene.search.Query; 14 | import org.apache.solr.common.SolrException; 15 | import org.apache.solr.request.SolrQueryRequest; 16 | import org.apache.solr.search.SolrIndexSearcher; 17 | import org.junit.Before; 18 | import org.junit.Test; 19 | import org.junit.runner.RunWith; 20 | 21 | import java.io.IOException; 22 | 23 | @RunWith(JMockit.class) 24 | public class RequestValidatorTest { 25 | 26 | @Mocked 27 | SolrQueryRequest solrRequest; 28 | @Mocked 29 | SolrIndexSearcher searcher; 30 | 31 | @Before 32 | public void init() throws IOException 33 | { 34 | new NonStrictExpectations() {{ 35 | solrRequest.getSearcher(); returns(searcher); 36 | }}; 37 | 38 | new MockUp() 39 | { 40 | @Mock void checkField(SolrQueryRequest req, String field, String facetField) {} 41 | }; 42 | 43 | new NodeContext(); 44 | } 45 | 46 | @Test(expected = SolrException.class) 47 | public void validate_NullQuery() throws IOException { 48 | KnowledgeGraphRequest request = new KnowledgeGraphRequest(); 49 | RequestValidator target = new RequestValidator(solrRequest, request); 50 | target.validate(); 51 | } 52 | 53 | @Test(expected = SolrException.class) 54 | public void validate_NullCompare() throws IOException { 55 | KnowledgeGraphRequest request = new KnowledgeGraphRequest(); 56 | request.queries = new String[] { "test" }; 57 | RequestValidator target = new RequestValidator(solrRequest, request); 58 | target.validate(); 59 | } 60 | 61 | @Test 62 | public void validate_OneCompare() throws IOException { 63 | KnowledgeGraphRequest request = new KnowledgeGraphRequest( 64 | new RequestNode[1]); 65 | request.queries = new String[] { "test" }; 66 | request.compare[0] = new RequestNode(null, "testType"); 67 | RequestValidator target = new RequestValidator(solrRequest, request); 68 | target.validate(); 69 | } 70 | 71 | @Test 72 | public void validate_TwoTrunkTreeCompare() throws IOException { 73 | new MockUp() { 74 | @Mock 75 | private Query parseQueryString(String qString, SolrQueryRequest req) 76 | { 77 | return new MatchAllDocsQuery(); 78 | } 79 | }; 80 | KnowledgeGraphRequest request = new KnowledgeGraphRequest( 81 | new RequestNode[2]); 82 | request.queries = new String[] { "test" }; 83 | request.normalize=true; 84 | request.compare[0] = new RequestNode(null, "testType0"); 85 | request.compare[1] = new RequestNode(null, "testType1"); 86 | request.compare[0].compare = new RequestNode[2]; 87 | request.compare[0].compare[0] = new RequestNode(null, "testType00"); 88 | request.compare[0].compare[1] = new RequestNode(null, "testType01"); 89 | ResponseNode[] expected = new ResponseNode[2]; 90 | RequestValidator target = new RequestValidator(solrRequest, request); 91 | target.validate(); 92 | } 93 | 94 | 95 | 96 | @Test(expected = SolrException.class) 97 | public void validate_TwoTrunkTreeCompareException() throws IOException { 98 | new MockUp() { 99 | @Mock 100 | private Query parseQueryString(String qString, SolrQueryRequest req) 101 | { 102 | return new MatchAllDocsQuery(); 103 | } 104 | }; 105 | KnowledgeGraphRequest request = new KnowledgeGraphRequest( 106 | new RequestNode[2]); 107 | request.queries = new String[] { "test" }; 108 | request.normalize=true; 109 | request.compare[0] = new RequestNode(null, "testType0"); 110 | request.compare[1] = new RequestNode(null, "testType1"); 111 | request.compare[0].compare = new RequestNode[2]; 112 | request.compare[0].compare[0] = new RequestNode(); 113 | request.compare[0].compare[1] = new RequestNode(null, "testType01"); 114 | RequestValidator target = new RequestValidator(solrRequest, request); 115 | target.validate(); 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /knowledge-graph/src/test/java/com/careerbuilder/search/relevancy/generation/FacetFieldAdapterTest.java: -------------------------------------------------------------------------------- 1 | package com.careerbuilder.search.relevancy.generation; 2 | 3 | import com.careerbuilder.search.relevancy.FieldChecker; 4 | import com.careerbuilder.search.relevancy.model.ParameterSet; 5 | import com.careerbuilder.search.relevancy.NodeContext; 6 | import mockit.Mock; 7 | import mockit.MockUp; 8 | import mockit.integration.junit4.JMockit; 9 | import org.apache.solr.common.SolrException; 10 | import org.apache.solr.common.params.MapSolrParams; 11 | import org.apache.solr.common.util.SimpleOrderedMap; 12 | import org.apache.solr.request.SolrQueryRequest; 13 | import org.junit.Assert; 14 | import org.junit.Before; 15 | import org.junit.Test; 16 | import org.junit.runner.RunWith; 17 | 18 | import java.io.IOException; 19 | import java.util.Arrays; 20 | import java.util.HashMap; 21 | import java.util.List; 22 | 23 | @RunWith(JMockit.class) 24 | public class FacetFieldAdapterTest { 25 | 26 | private MapSolrParams invariants; 27 | private List fieldList; 28 | private String[] fieldNames = new String[] 29 | { 30 | "title", 31 | "title.top", 32 | "title.id-title", 33 | "title.top.id-title", 34 | "tags", 35 | "tags.top", 36 | "tags.id-title", 37 | "tags.top.id-title", 38 | "rank", 39 | "rank.level-description", 40 | "field.with.dots", 41 | "field.with.dots.id-title", 42 | "field.with.dots.id" 43 | }; 44 | 45 | @Before 46 | public void init() { 47 | HashMap paramMap = new HashMap<>(); 48 | paramMap.put("title.facet-field", "id-title"); 49 | paramMap.put("title.key", "id"); 50 | paramMap.put("title.top.facet-field", "id-title"); 51 | paramMap.put("tags.facet-field", "id-title"); 52 | paramMap.put("tags.key", "id"); 53 | paramMap.put("tags.top.facet-field", "id-title"); 54 | paramMap.put("tags.top.key", "id"); 55 | paramMap.put("rank.facet-field", "level-description"); 56 | paramMap.put("rank.key", "level"); 57 | paramMap.put("field.with.dots.facet-field", "id-value"); 58 | paramMap.put("field.with.dots.key", "id"); 59 | 60 | new MockUp() 61 | { 62 | @Mock void checkField(SolrQueryRequest req, String field, String facetField) 63 | { 64 | if(!fieldList.contains(field)) 65 | throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "you tell me do things i come runnin"); 66 | } 67 | }; 68 | 69 | fieldList = Arrays.asList(fieldNames); 70 | invariants = new MapSolrParams(paramMap); 71 | } 72 | 73 | 74 | @Test(expected = SolrException.class) 75 | public void testAdaptNonExistantField() throws IOException 76 | { 77 | NodeContext context = new NodeContext(new ParameterSet(null, null, invariants)); 78 | FacetFieldAdapter target = new FacetFieldAdapter(context, "bogus"); 79 | } 80 | 81 | 82 | @Test 83 | public void testAdaptTitle() throws IOException 84 | { 85 | NodeContext context = new NodeContext(new ParameterSet(null, null, invariants)); 86 | FacetFieldAdapter target = new FacetFieldAdapter(context, "title"); 87 | 88 | String actual = target.field; 89 | Assert.assertEquals("title.id-title", actual); 90 | } 91 | 92 | @Test 93 | public void testAdaptTitleTop() 94 | { 95 | NodeContext context = new NodeContext(new ParameterSet(null, null, invariants)); 96 | FacetFieldAdapter target = new FacetFieldAdapter(context, "title.top"); 97 | 98 | String actual = target.field; 99 | Assert.assertEquals("title.top.id-title", actual); 100 | } 101 | 102 | @Test 103 | public void testAdaptRank() throws IOException 104 | { 105 | NodeContext context = new NodeContext(new ParameterSet(null,null,invariants)); 106 | FacetFieldAdapter target = new FacetFieldAdapter(context, "rank"); 107 | 108 | String actual = target.field; 109 | Assert.assertEquals("rank.level-description", actual); 110 | } 111 | 112 | 113 | @Test 114 | public void getMapValue_Rank() throws IOException 115 | { 116 | NodeContext context = new NodeContext(new ParameterSet(null, null, invariants)); 117 | FacetFieldAdapter target = new FacetFieldAdapter(context, "rank"); 118 | 119 | SimpleOrderedMap resultBucket = new SimpleOrderedMap<>(); 120 | resultBucket.add("val", "99^testdescription"); 121 | SimpleOrderedMap actual = target.getMapValue(resultBucket); 122 | 123 | Assert.assertEquals("99", actual.get("level")); 124 | Assert.assertEquals("testdescription", actual.get("description")); 125 | } 126 | 127 | @Test 128 | public void getStringValue_Rank() throws IOException 129 | { 130 | NodeContext context = new NodeContext(new ParameterSet(null,null,invariants)); 131 | FacetFieldAdapter target = new FacetFieldAdapter(context, "rank"); 132 | 133 | SimpleOrderedMap resultBucket = new SimpleOrderedMap<>(); 134 | resultBucket.add("val", "99^testdescription"); 135 | String actual = target.getStringValue(resultBucket); 136 | 137 | Assert.assertEquals("99", actual); 138 | } 139 | 140 | @Test 141 | public void getMapValue_Title() throws IOException 142 | { 143 | NodeContext context = new NodeContext(new ParameterSet(null,null,invariants)); 144 | FacetFieldAdapter target = new FacetFieldAdapter(context, "title"); 145 | 146 | SimpleOrderedMap resultBucket = new SimpleOrderedMap<>(); 147 | resultBucket.add("val", "99^testtitle"); 148 | SimpleOrderedMap actual = target.getMapValue(resultBucket); 149 | 150 | Assert.assertEquals("99", actual.get("id")); 151 | Assert.assertEquals("testtitle", actual.get("title")); 152 | } 153 | 154 | @Test 155 | public void getStringValue_Title() throws IOException 156 | { 157 | NodeContext context = new NodeContext(new ParameterSet(null,null,invariants)); 158 | FacetFieldAdapter target = new FacetFieldAdapter(context, "title"); 159 | 160 | SimpleOrderedMap resultBucket = new SimpleOrderedMap<>(); 161 | resultBucket.add("val", "99^testtitle"); 162 | String actual = target.getStringValue(resultBucket); 163 | 164 | Assert.assertEquals("99", actual); 165 | } 166 | 167 | @Test 168 | public void getMapValue_Tags() throws IOException 169 | { 170 | NodeContext context = new NodeContext(new ParameterSet(null,null,invariants)); 171 | FacetFieldAdapter target = new FacetFieldAdapter(context, "tags"); 172 | 173 | SimpleOrderedMap resultBucket = new SimpleOrderedMap<>(); 174 | resultBucket.add("val", "99^testtitle"); 175 | SimpleOrderedMap actual = target.getMapValue(resultBucket); 176 | 177 | Assert.assertEquals("99", actual.get("id")); 178 | Assert.assertEquals("testtitle", actual.get("title")); 179 | } 180 | 181 | 182 | @Test 183 | public void getStringValue_Tags() throws IOException 184 | { 185 | NodeContext context = new NodeContext(new ParameterSet(null,null,invariants)); 186 | FacetFieldAdapter target = new FacetFieldAdapter(context, "tags"); 187 | 188 | SimpleOrderedMap resultBucket = new SimpleOrderedMap<>(); 189 | resultBucket.add("val", "99^testtitle"); 190 | String actual = target.getStringValue(resultBucket); 191 | 192 | Assert.assertEquals("99", actual); 193 | } 194 | 195 | @Test 196 | public void getMapValue_FieldWithDots() throws IOException 197 | { 198 | NodeContext context = new NodeContext(new ParameterSet(null,null,invariants)); 199 | FacetFieldAdapter target = new FacetFieldAdapter(context, "field.with.dots"); 200 | 201 | SimpleOrderedMap resultBucket = new SimpleOrderedMap<>(); 202 | resultBucket.add("val", "99^testfieldvalue"); 203 | SimpleOrderedMap actual = target.getMapValue(resultBucket); 204 | 205 | Assert.assertEquals("99", actual.get("id")); 206 | Assert.assertEquals("testfieldvalue", actual.get("value")); 207 | } 208 | 209 | @Test 210 | public void getStringValue_FieldWithDots() throws IOException 211 | { 212 | NodeContext context = new NodeContext(new ParameterSet(null,null,invariants)); 213 | FacetFieldAdapter target = new FacetFieldAdapter(context, "field.with.dots"); 214 | 215 | SimpleOrderedMap resultBucket = new SimpleOrderedMap<>(); 216 | resultBucket.add("val", "99^testvalue"); 217 | String actual = target.getStringValue(resultBucket); 218 | 219 | Assert.assertEquals("99", actual); 220 | } 221 | 222 | } -------------------------------------------------------------------------------- /knowledge-graph/src/test/java/com/careerbuilder/search/relevancy/generation/NodeGeneratorTest.java: -------------------------------------------------------------------------------- 1 | package com.careerbuilder.search.relevancy.generation; 2 | 3 | import com.careerbuilder.search.relevancy.utility.MapUtility; 4 | import com.careerbuilder.search.relevancy.model.KnowledgeGraphRequest; 5 | import com.careerbuilder.search.relevancy.model.RequestNode; 6 | import com.careerbuilder.search.relevancy.model.ResponseNode; 7 | import com.careerbuilder.search.relevancy.model.ResponseValue; 8 | import com.careerbuilder.search.relevancy.NodeContext; 9 | import com.careerbuilder.search.relevancy.waitable.AggregationWaitable; 10 | import mockit.*; 11 | import mockit.integration.junit4.JMockit; 12 | import org.apache.lucene.search.Query; 13 | import org.apache.lucene.search.Sort; 14 | import org.apache.solr.common.util.SimpleOrderedMap; 15 | import org.apache.solr.request.SolrQueryRequest; 16 | import org.apache.solr.search.DocListAndSet; 17 | import org.apache.solr.search.DocSet; 18 | import org.apache.solr.search.SolrIndexSearcher; 19 | import org.junit.Assert; 20 | import org.junit.Before; 21 | import org.junit.Test; 22 | import org.junit.runner.RunWith; 23 | 24 | import java.io.IOException; 25 | import java.util.*; 26 | 27 | @RunWith(JMockit.class) 28 | public class NodeGeneratorTest { 29 | 30 | ResponseNode response; 31 | RequestNode request; 32 | AggregationWaitable runner; 33 | @Cascading final NodeContext context = new NodeContext(new KnowledgeGraphRequest()); 34 | @Mocked SolrQueryRequest unused; 35 | @Mocked SolrIndexSearcher unusedSearcher; 36 | FacetFieldAdapter adapter; 37 | 38 | @Before 39 | public void init() { 40 | 41 | request = new RequestNode(null, "testType"); 42 | request.values = new String[] {"passedInValue1", "passedInValue2"}; 43 | 44 | response = new ResponseNode("testType"); 45 | context.req = unused; 46 | 47 | new MockUp() 48 | { 49 | @Mock 50 | public DocListAndSet getDocListAndSet(Query q, DocSet d, Sort s, int one, int two) 51 | { 52 | return null; 53 | } 54 | }; 55 | 56 | new MockUp () { 57 | @Mock public void $init(NodeContext context, String field) { } 58 | @Mock public String getStringValue(SimpleOrderedMap bucket) { 59 | return (String)bucket.get("val"); 60 | } 61 | @Mock public SimpleOrderedMap getMapValue(SimpleOrderedMap bucket) { 62 | SimpleOrderedMap map = new SimpleOrderedMap<>(); 63 | map.add("name", (String)bucket.get("val")); 64 | return map; 65 | } 66 | }; 67 | 68 | new NonStrictExpectations() {{ 69 | context.req.getSearcher(); returns(unusedSearcher); 70 | }}; 71 | 72 | adapter = new FacetFieldAdapter(null, "testField"); 73 | Deencapsulation.setField(adapter, "facetFieldValueDelimiter", "^"); 74 | runner = new AggregationWaitable(null, adapter, null, "testField",0, 0); 75 | } 76 | 77 | @Test 78 | public void buildWaitables_noDiscover() 79 | { 80 | RequestNode [] requests = new RequestNode[1]; 81 | FacetFieldAdapter [] adapters = new FacetFieldAdapter[1]; 82 | requests[0] = new RequestNode(null, "testField"); 83 | 84 | NodeGenerator target = new NodeGenerator(); 85 | AggregationWaitable[] runners = Deencapsulation.invoke(target, "buildWaitables", context, requests); 86 | 87 | Assert.assertEquals(null, runners[0]); 88 | } 89 | 90 | @Test 91 | public void buildWaitables_discover() 92 | { 93 | RequestNode [] requests = new RequestNode[1]; 94 | requests[0] = new RequestNode(null, "testField"); 95 | requests[0].limit = 10; 96 | requests[0].discover_values = true; 97 | 98 | new Expectations() {{ 99 | new AggregationWaitable(context, (FacetFieldAdapter)any, null, 0, 10); 100 | }}; 101 | 102 | NodeGenerator target = new NodeGenerator(); 103 | AggregationWaitable[] actual = Deencapsulation.invoke(target, "buildWaitables", context, requests); 104 | Assert.assertNotEquals(null, actual[0]); 105 | } 106 | 107 | 108 | @Test 109 | public void addPassedInValues_noNormalized() throws IOException 110 | { 111 | ResponseNode response = new ResponseNode("testField"); 112 | response.values = new ResponseValue[2]; 113 | ResponseValue [] expecteds = new ResponseValue[2]; 114 | expecteds[0] = new ResponseValue("passedInValue1"); 115 | expecteds[1] = new ResponseValue("passedInValue2"); 116 | 117 | NodeGenerator target = new NodeGenerator(); 118 | Deencapsulation.invoke(target, "addPassedInValues", request, response); 119 | 120 | Assert.assertEquals(2, response.values.length); 121 | for(ResponseValue expected : expecteds) { 122 | Assert.assertTrue(Arrays.asList(response.values).contains(expected)); 123 | } 124 | 125 | } 126 | 127 | @Test 128 | public void addPassedInValues_normalized() throws IOException 129 | { 130 | ResponseNode response = new ResponseNode("testField"); 131 | response.values = new ResponseValue[2]; 132 | ResponseValue [] expecteds = new ResponseValue[2]; 133 | expecteds[0] = new ResponseValue("passedInValue1"); 134 | expecteds[0].normalizedValue = new SimpleOrderedMap<>(); 135 | expecteds[0].normalizedValue.add("name", "passedInValue1"); 136 | expecteds[1] = new ResponseValue("passedInValue2"); 137 | expecteds[1].normalizedValue = new SimpleOrderedMap<>(); 138 | expecteds[1].normalizedValue.add("name", "passedInValue2"); 139 | request.normalizedValues = new LinkedList<>(); 140 | request.normalizedValues.add(expecteds[0].normalizedValue); 141 | request.normalizedValues.add(expecteds[1].normalizedValue); 142 | 143 | NodeGenerator target = new NodeGenerator(); 144 | Deencapsulation.invoke(target, "addPassedInValues", request, response); 145 | 146 | Assert.assertEquals(2, response.values.length); 147 | for(int i = 0; i < expecteds.length; ++i) { 148 | Assert.assertTrue(response.values[i].equals(expecteds[i])); 149 | Assert.assertTrue(MapUtility.mapsEqual(response.values[i].normalizedValue, expecteds[i].normalizedValue)); 150 | } 151 | 152 | } 153 | 154 | @Test 155 | public void merge() throws IOException 156 | { 157 | RequestNode request = new RequestNode(null, "type"); 158 | NodeGenerator target = new NodeGenerator(); 159 | new Expectations(target){{ 160 | Deencapsulation.invoke(target, "addPassedInValues", request, response); returns(1); 161 | Deencapsulation.invoke(target, "addGeneratedValues", response, runner, 1); 162 | }}; 163 | 164 | Deencapsulation.invoke(target, "mergeResponseValues", request, response, runner); 165 | } 166 | 167 | @Test 168 | public void addGeneratedValues() throws IOException 169 | { 170 | ResponseNode response = new ResponseNode("testField"); 171 | response.values = new ResponseValue[2]; 172 | 173 | runner.buckets = new LinkedList<>(); 174 | SimpleOrderedMap generatedValue1 = new SimpleOrderedMap<>(); 175 | generatedValue1.add("val", "generatedValue1"); 176 | SimpleOrderedMap generatedValue2 = new SimpleOrderedMap<>(); 177 | generatedValue2.add("val", "generatedValue2"); 178 | runner.buckets.add(generatedValue1); 179 | runner.buckets.add(generatedValue2); 180 | ResponseValue [] expecteds = new ResponseValue[2]; 181 | expecteds[0] = new ResponseValue("generatedValue1"); 182 | expecteds[0].normalizedValue = new SimpleOrderedMap<>(); 183 | expecteds[0].normalizedValue.add("name", "generatedValue1"); 184 | expecteds[1] = new ResponseValue("generatedValue2"); 185 | expecteds[1].normalizedValue = new SimpleOrderedMap<>(); 186 | expecteds[1].normalizedValue.add("name", "generatedValue2"); 187 | 188 | NodeGenerator target = new NodeGenerator(); 189 | Deencapsulation.invoke(target, "addGeneratedValues", response, runner, 0); 190 | 191 | Assert.assertEquals(2, response.values.length); 192 | for(int i = 0; i < expecteds.length; ++i) { 193 | Assert.assertTrue(response.values[i].equals(expecteds[i])); 194 | Assert.assertTrue(MapUtility.mapsEqual(response.values[i].normalizedValue, expecteds[i].normalizedValue)); 195 | } 196 | } 197 | 198 | } 199 | -------------------------------------------------------------------------------- /knowledge-graph/src/test/java/com/careerbuilder/search/relevancy/normalization/NodeNormalizerTest.java: -------------------------------------------------------------------------------- 1 | package com.careerbuilder.search.relevancy.normalization; 2 | 3 | import com.careerbuilder.search.relevancy.generation.FacetFieldAdapter; 4 | import com.careerbuilder.search.relevancy.model.KnowledgeGraphRequest; 5 | import com.careerbuilder.search.relevancy.model.RequestNode; 6 | import com.careerbuilder.search.relevancy.model.ResponseNode; 7 | import com.careerbuilder.search.relevancy.NodeContext; 8 | import com.careerbuilder.search.relevancy.waitable.AggregationWaitable; 9 | import mockit.*; 10 | import mockit.integration.junit4.JMockit; 11 | import org.apache.lucene.search.Query; 12 | import org.apache.lucene.search.Sort; 13 | import org.apache.solr.common.util.SimpleOrderedMap; 14 | import org.apache.solr.request.SolrQueryRequest; 15 | import org.apache.solr.search.DocListAndSet; 16 | import org.apache.solr.search.DocSet; 17 | import org.apache.solr.search.SolrIndexSearcher; 18 | import org.junit.Assert; 19 | import org.junit.Before; 20 | import org.junit.Test; 21 | import org.junit.runner.RunWith; 22 | 23 | import java.io.IOException; 24 | import java.util.LinkedList; 25 | import java.util.List; 26 | import java.util.Map; 27 | import java.util.TreeMap; 28 | 29 | @RunWith(JMockit.class) 30 | public class NodeNormalizerTest { 31 | 32 | ResponseNode response; 33 | RequestNode request; 34 | @Mocked 35 | AggregationWaitable runner; 36 | @Cascading final NodeContext context = new NodeContext(new KnowledgeGraphRequest()); 37 | @Mocked SolrQueryRequest unused; 38 | @Mocked SolrIndexSearcher unusedSearcher; 39 | 40 | @Before 41 | public void init() { 42 | runner.buckets= new LinkedList<>(); 43 | 44 | request = new RequestNode(null, "testType"); 45 | request.values = new String[] {"passedInValue1", "passedInValue2"}; 46 | 47 | response = new ResponseNode("testType"); 48 | context.req = unused; 49 | 50 | new MockUp() 51 | { 52 | @Mock 53 | public DocListAndSet getDocListAndSet(Query q, DocSet d, Sort s, int one, int two) 54 | { 55 | return null; 56 | } 57 | }; 58 | 59 | new NonStrictExpectations() {{ 60 | context.req.getSearcher(); returns(unusedSearcher); 61 | }}; 62 | 63 | new MockUp() { 64 | @Mock public void $init(NodeContext context, String field) {} 65 | @Mock public String getStringValue(SimpleOrderedMap bucket) { 66 | return (String)bucket.get("val"); 67 | } 68 | @Mock public SimpleOrderedMap getMapValue(SimpleOrderedMap bucket) { 69 | SimpleOrderedMap map = new SimpleOrderedMap<>(); 70 | map.add("name", (String)bucket.get("val")); 71 | map.add("id", (String)bucket.get("id")); 72 | return map; 73 | } 74 | }; 75 | 76 | } 77 | 78 | @Test 79 | public void buildRunners_noValues() 80 | { 81 | RequestNode [] requests = new RequestNode[1]; 82 | FacetFieldAdapter [] adapters = new FacetFieldAdapter[1]; 83 | adapters[0] = new FacetFieldAdapter("testField"); 84 | Deencapsulation.setField(adapters[0], "facetFieldExtension", ".cs"); 85 | requests[0] = new RequestNode(null, "testField"); 86 | NodeNormalizer target = new NodeNormalizer(); 87 | 88 | Map> runners = Deencapsulation.invoke(target, "buildRunners", context, requests); 89 | 90 | Assert.assertEquals(0, runners.get("testField").size()); 91 | } 92 | 93 | @Test 94 | public void buildRunners_noExtension() 95 | { 96 | RequestNode [] requests = new RequestNode[1]; 97 | FacetFieldAdapter [] adapters = new FacetFieldAdapter[1]; 98 | adapters[0] = new FacetFieldAdapter("testField"); 99 | requests[0] = new RequestNode(null, "testField"); 100 | requests[0].values = new String[] {"testValue"}; 101 | NodeNormalizer target = new NodeNormalizer(); 102 | 103 | Map> runners = Deencapsulation.invoke(target, "buildRunners", context, requests); 104 | 105 | Assert.assertEquals(0, runners.get("testField").size()); 106 | } 107 | 108 | @Test 109 | public void buildRunners_Normalize(@Mocked FacetFieldAdapter adapter) throws IOException 110 | { 111 | RequestNode [] requests = new RequestNode[1]; 112 | Deencapsulation.setField(adapter, "facetFieldExtension", ".cs"); 113 | requests[0] = new RequestNode(null, "testField"); 114 | requests[0].values = new String[] {"testValue"}; 115 | NodeNormalizer target = new NodeNormalizer(); 116 | 117 | new Expectations() {{ 118 | new FacetFieldAdapter(context, "testField"); 119 | adapter.hasExtension(); returns(true); 120 | new AggregationWaitable(context, adapter, "null:\"testvalue\"", null, 0, 100); 121 | }}; 122 | 123 | Map> runners = Deencapsulation.invoke(target, "buildRunners", context, requests); 124 | } 125 | 126 | @Test 127 | public void populateNorms() 128 | { 129 | NodeNormalizer target = new NodeNormalizer(); 130 | FacetFieldAdapter adapter = new FacetFieldAdapter("testField"); 131 | AggregationWaitable runner = new AggregationWaitable(context, adapter, "testField", 0, 1); 132 | runner.buckets = new LinkedList<>(); 133 | runner.adapter = adapter; 134 | SimpleOrderedMap bucket1 = new SimpleOrderedMap<>(); 135 | bucket1.add("val", "testValue1"); 136 | bucket1.add("id", "1"); 137 | SimpleOrderedMap bucket2 = new SimpleOrderedMap<>(); 138 | bucket2.add("val", "testValue2"); 139 | bucket2.add("id", "2"); 140 | SimpleOrderedMap bucket3 = new SimpleOrderedMap<>(); 141 | bucket3.add("val", "value3"); 142 | bucket3.add("id", "3"); 143 | runner.buckets.add(bucket1); 144 | runner.buckets.add(bucket2); 145 | runner.buckets.add(bucket3); 146 | String requestValue1 = "testValue1"; 147 | String requestValue2 = "testValue2"; 148 | LinkedList normalizedStrings = new LinkedList<>(); 149 | LinkedList> normalizedMaps = new LinkedList<>(); 150 | String [] expectedStrings = new String [] {"testValue1", "testValue2"}; 151 | LinkedList> expectedMaps = new LinkedList<>(); 152 | SimpleOrderedMap map1 = new SimpleOrderedMap<>(); 153 | map1.add("name", "testValue1"); 154 | map1.add("id", "1"); 155 | SimpleOrderedMap map2 = new SimpleOrderedMap<>(); 156 | map2.add("name", "testValue2"); 157 | map2.add("id", "2"); 158 | expectedMaps.add(map1); 159 | expectedMaps.add(map2); 160 | 161 | Deencapsulation.invoke(target, "populateNorms", runner, requestValue1, normalizedStrings, normalizedMaps); 162 | Deencapsulation.invoke(target, "populateNorms", runner, requestValue2, normalizedStrings, normalizedMaps); 163 | 164 | Assert.assertEquals(2, normalizedStrings.size()); 165 | Assert.assertEquals(2, normalizedMaps.size()); 166 | for(int i = 0; i < expectedStrings.length ; ++i) { 167 | Assert.assertEquals(expectedMaps.get(i),normalizedMaps.get(i)); 168 | Assert.assertEquals(expectedStrings[i],normalizedStrings.get(i)); 169 | } 170 | } 171 | 172 | @Test 173 | public void populateNorms_Id() 174 | { 175 | NodeNormalizer target = new NodeNormalizer(); 176 | FacetFieldAdapter adapter = new FacetFieldAdapter("testField"); 177 | AggregationWaitable runner = new AggregationWaitable(context, adapter, "testField", 0, 1); 178 | runner.buckets = new LinkedList<>(); 179 | runner.adapter = adapter; 180 | SimpleOrderedMap bucket1 = new SimpleOrderedMap<>(); 181 | bucket1.add("val", "testValue1"); 182 | bucket1.add("id", "1"); 183 | SimpleOrderedMap bucket2 = new SimpleOrderedMap<>(); 184 | bucket2.add("val", "testValue2"); 185 | bucket2.add("id", "2"); 186 | SimpleOrderedMap bucket3 = new SimpleOrderedMap<>(); 187 | bucket3.add("val", "value3"); 188 | bucket3.add("id", "3"); 189 | runner.buckets.add(bucket1); 190 | runner.buckets.add(bucket2); 191 | runner.buckets.add(bucket3); 192 | String requestValue1 = "1"; 193 | String requestValue2 = "2"; 194 | LinkedList normalizedStrings = new LinkedList<>(); 195 | LinkedList> normalizedMaps = new LinkedList<>(); 196 | String [] expectedStrings = new String [] {"testValue1", "testValue2"}; 197 | LinkedList> expectedMaps = new LinkedList<>(); 198 | SimpleOrderedMap map1 = new SimpleOrderedMap<>(); 199 | map1.add("name", "testValue1"); 200 | map1.add("id", "1"); 201 | SimpleOrderedMap map2 = new SimpleOrderedMap<>(); 202 | map2.add("name", "testValue2"); 203 | map2.add("id", "2"); 204 | expectedMaps.add(map1); 205 | expectedMaps.add(map2); 206 | 207 | 208 | Deencapsulation.invoke(target, "populateNorms", runner, requestValue1, normalizedStrings, normalizedMaps); 209 | Deencapsulation.invoke(target, "populateNorms", runner, requestValue2, normalizedStrings, normalizedMaps); 210 | 211 | Assert.assertEquals(2, normalizedStrings.size()); 212 | Assert.assertEquals(2, normalizedMaps.size()); 213 | for(int i = 0; i < expectedStrings.length ; ++i) { 214 | Assert.assertEquals(expectedMaps.get(i),normalizedMaps.get(i)); 215 | Assert.assertEquals(expectedStrings[i],normalizedStrings.get(i)); 216 | } 217 | } 218 | 219 | @Test 220 | public void normalizeRequests() { 221 | RequestNode [] requests = new RequestNode[1]; 222 | requests[0] = new RequestNode(null, "testField"); 223 | requests[0].values = new String[] {"testValue1"}; 224 | NodeNormalizer target = new NodeNormalizer(); 225 | FacetFieldAdapter adapter = new FacetFieldAdapter("testField"); 226 | Deencapsulation.setField(adapter, "facetFieldExtension", ".cs"); 227 | Map> runners = new TreeMap<>(); 228 | List runnerList = new LinkedList<>(); 229 | runnerList.add(new AggregationWaitable(context, adapter, "testField", 0, 1)); 230 | runnerList.get(0).buckets = new LinkedList<>(); 231 | runnerList.get(0).adapter = adapter; 232 | SimpleOrderedMap bucket1 = new SimpleOrderedMap<>(); 233 | bucket1.add("val", "testValue1"); 234 | SimpleOrderedMap bucket2 = new SimpleOrderedMap<>(); 235 | bucket2.add("val", "testValue2"); 236 | SimpleOrderedMap bucket3 = new SimpleOrderedMap<>(); 237 | bucket3.add("val", "value3"); 238 | runnerList.get(0).buckets.add(bucket1); 239 | runnerList.get(0).buckets.add(bucket2); 240 | runnerList.get(0).buckets.add(bucket3); 241 | runners.put("testField", runnerList); 242 | String [] expectedStrings = new String [] {"testValue1"}; 243 | LinkedList> expectedMaps = new LinkedList<>(); 244 | SimpleOrderedMap map1 = new SimpleOrderedMap<>(); 245 | map1.add("name", "testValue1"); 246 | map1.add("id", null); 247 | SimpleOrderedMap map2 = new SimpleOrderedMap<>(); 248 | map2.add("name", "testValue2"); 249 | map2.add("id", null); 250 | expectedMaps.add(map1); 251 | expectedMaps.add(map2); 252 | 253 | target.normalizeRequests(requests, runners); 254 | 255 | Assert.assertEquals(1, requests[0].values.length); 256 | Assert.assertEquals(1, requests[0].normalizedValues.size()); 257 | for(int i = 0; i < expectedStrings.length ; ++i) { 258 | Assert.assertEquals(expectedMaps.get(i),requests[0].normalizedValues.get(i)); 259 | Assert.assertEquals(expectedStrings[i],requests[0].values[i]); 260 | } 261 | } 262 | } 263 | -------------------------------------------------------------------------------- /knowledge-graph/src/test/java/com/careerbuilder/search/relevancy/responsewriter/KnowledgeGraphResponseWriterTest.java: -------------------------------------------------------------------------------- 1 | package com.careerbuilder.search.relevancy.responsewriter; 2 | 3 | import com.careerbuilder.search.relevancy.model.KnowledgeGraphResponse; 4 | import com.careerbuilder.search.relevancy.model.ResponseNode; 5 | import com.careerbuilder.search.relevancy.model.ResponseValue; 6 | import mockit.Mock; 7 | import mockit.MockUp; 8 | import mockit.integration.junit4.JMockit; 9 | import org.apache.solr.common.SolrException; 10 | import org.apache.solr.common.util.NamedList; 11 | import org.apache.solr.request.LocalSolrQueryRequest; 12 | import org.apache.solr.request.SolrQueryRequest; 13 | import org.apache.solr.response.SolrQueryResponse; 14 | import org.junit.Assert; 15 | import org.junit.Before; 16 | import org.junit.Test; 17 | import org.junit.runner.RunWith; 18 | 19 | import java.io.IOException; 20 | import java.io.StringWriter; 21 | import java.io.Writer; 22 | import java.util.HashMap; 23 | 24 | @RunWith(JMockit.class) 25 | public class KnowledgeGraphResponseWriterTest 26 | { 27 | 28 | HashMap dummy = new HashMap<>(); 29 | SolrQueryRequest request; 30 | SolrQueryResponse response; 31 | 32 | @Before 33 | public void init() 34 | { 35 | 36 | new MockUp() 37 | { 38 | @Mock public NamedList getResponseHeader() 39 | { 40 | NamedList headers = new NamedList<>(); 41 | headers.add("status", 400); 42 | return headers; 43 | } 44 | }; 45 | request = new LocalSolrQueryRequest(null, dummy); 46 | response = new SolrQueryResponse(); 47 | response.setHttpHeader("status", "400"); 48 | } 49 | 50 | @Test 51 | public void write() throws IOException 52 | { 53 | 54 | ResponseNode[] responses = new ResponseNode[1]; 55 | responses[0] = new ResponseNode("testType"); 56 | responses[0].values = new ResponseValue[1]; 57 | responses[0].values[0] = new ResponseValue("testValue", 1.0); 58 | KnowledgeGraphResponse relResponse = new KnowledgeGraphResponse(); 59 | relResponse.data = responses; 60 | response.add("relatednessResponse", relResponse); 61 | KnowledgeGraphResponseWriter target = new KnowledgeGraphResponseWriter(); 62 | Writer writer = new StringWriter(); 63 | 64 | target.write(writer, request, response); 65 | 66 | Assert.assertEquals("{\"data\":[{\"type\":\"testType\",\"values\":[{\"name\":\"testValue\",\"relatedness\":0.0,\"popularity\":0.0,\"foreground_popularity\":1.0,\"background_popularity\":0.0}]}]}" 67 | , writer.toString()); 68 | } 69 | 70 | @Test 71 | public void write_Exception() throws IOException 72 | { 73 | 74 | response.setException(new SolrException(SolrException.ErrorCode.BAD_REQUEST, "This is a test of the emergency alert system")); 75 | KnowledgeGraphResponseWriter target = new KnowledgeGraphResponseWriter(); 76 | Writer writer = new StringWriter(); 77 | 78 | target.write(writer, request, response); 79 | 80 | Assert.assertEquals("{\"error\":{\"msg\":\"This is a test of the emergency alert system\",\"code\":400}}" 81 | , writer.toString()); 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /knowledge-graph/src/test/java/com/careerbuilder/search/relevancy/responsewriter/ResponseValueSerializerTest.java: -------------------------------------------------------------------------------- 1 | package com.careerbuilder.search.relevancy.responsewriter; 2 | 3 | import com.careerbuilder.search.relevancy.model.ResponseValue; 4 | import com.google.gson.Gson; 5 | import com.google.gson.GsonBuilder; 6 | import mockit.integration.junit4.JMockit; 7 | import org.apache.solr.common.util.SimpleOrderedMap; 8 | import org.junit.Assert; 9 | import org.junit.Test; 10 | import org.junit.runner.RunWith; 11 | 12 | @RunWith(JMockit.class) 13 | public class ResponseValueSerializerTest { 14 | 15 | @Test 16 | public void serialize_facetValue() 17 | { 18 | ResponseValue r1 = new ResponseValue("12 test1", 1.0); 19 | r1.normalizedValue = new SimpleOrderedMap<>(); 20 | r1.normalizedValue.add("id", "12"); 21 | r1.normalizedValue.add("title", "test1"); 22 | 23 | Gson gson = new GsonBuilder().registerTypeAdapter(ResponseValue.class, new ResponseValueSerializer()).create(); 24 | 25 | String json = gson.toJson(r1); 26 | 27 | Assert.assertEquals("{\"id\":\"12\",\"title\":\"test1\",\"relatedness\":0.0,\"popularity\":0.0,\"foreground_popularity\":1.0,\"background_popularity\":0.0}", 28 | json); 29 | } 30 | 31 | @Test 32 | public void serialize_value() 33 | { 34 | ResponseValue r1 = new ResponseValue("12 test1", 1.0); 35 | 36 | Gson gson = new GsonBuilder().registerTypeAdapter(ResponseValue.class, new ResponseValueSerializer()).create(); 37 | 38 | String json = gson.toJson(r1); 39 | 40 | Assert.assertEquals("{\"name\":\"12 test1\",\"relatedness\":0.0,\"popularity\":0.0,\"foreground_popularity\":1.0,\"background_popularity\":0.0}", 41 | json); 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /knowledge-graph/src/test/java/com/careerbuilder/search/relevancy/scoring/BackupScorerTest.java: -------------------------------------------------------------------------------- 1 | package com.careerbuilder.search.relevancy.scoring; 2 | 3 | import com.careerbuilder.search.relevancy.model.RequestNode; 4 | import com.careerbuilder.search.relevancy.model.ResponseNode; 5 | import com.careerbuilder.search.relevancy.model.ResponseValue; 6 | import com.careerbuilder.search.relevancy.waitable.QueryWaitable; 7 | import mockit.Mocked; 8 | import mockit.integration.junit4.JMockit; 9 | import org.apache.solr.search.DocSet; 10 | import org.junit.Assert; 11 | import org.junit.Before; 12 | import org.junit.Test; 13 | import org.junit.runner.RunWith; 14 | 15 | import java.io.IOException; 16 | import java.util.*; 17 | 18 | @RunWith(JMockit.class) 19 | public class BackupScorerTest 20 | { 21 | 22 | QueryWaitable[] fgRunners = new QueryWaitable[4]; 23 | QueryWaitable[] replacements = new QueryWaitable[2]; 24 | 25 | ResponseNode response = new ResponseNode(); 26 | RequestNode request = new RequestNode(); 27 | List runners = new LinkedList<>(); 28 | List replacementRunners = new LinkedList<>(); 29 | @Mocked 30 | DocSet fgDomain; 31 | @Mocked 32 | DocSet bgDomain; 33 | @Mocked 34 | ScoreNormalizer normalizer; 35 | 36 | @Before 37 | public void init() 38 | { 39 | response.type = "keywords.v1"; 40 | response.values = new ResponseValue[0]; 41 | fgRunners[0] = new QueryWaitable(null, null, null, QueryWaitable.QueryType.FG, 0); 42 | fgRunners[1] = new QueryWaitable(null, null, null, QueryWaitable.QueryType.FG, 1); 43 | fgRunners[2] = new QueryWaitable(null, null, null, QueryWaitable.QueryType.FG, 2); 44 | fgRunners[3] = new QueryWaitable(null, null, null, QueryWaitable.QueryType.FG, 3); 45 | fgRunners[0].result = 0; 46 | fgRunners[1].result = 3; 47 | fgRunners[2].result = 1; 48 | fgRunners[3].result = 3; 49 | 50 | replacements[0] = new QueryWaitable(null, null, null, QueryWaitable.QueryType.FG, 0); 51 | replacements[1] = new QueryWaitable(null, null, null, QueryWaitable.QueryType.FG, 2); 52 | 53 | replacements[0].result = 271; 54 | replacements[1].result = 271; 55 | 56 | request.limit = 2; 57 | 58 | runners.addAll(Arrays.asList(fgRunners)); 59 | replacementRunners.addAll(Arrays.asList(replacements)); 60 | } 61 | 62 | @Test 63 | public void getFallbackIndices0Min() throws IOException 64 | { 65 | BackupScorer target = new BackupScorer(); 66 | Set actual = target.getFallbackIndices(runners, 0.0); 67 | 68 | Assert.assertEquals(1, actual.size()); 69 | Assert.assertEquals(new Integer(0), actual.iterator().next()); 70 | } 71 | 72 | @Test 73 | public void getFallbackIndices1point5Min() throws IOException 74 | { 75 | BackupScorer target = new BackupScorer(); 76 | Set actual = target.getFallbackIndices(runners, 1.5); 77 | 78 | Iterator resultIt = actual.iterator(); 79 | Assert.assertEquals(2, actual.size()); 80 | Assert.assertEquals(new Integer(0), resultIt.next()); 81 | Assert.assertEquals(new Integer(2), resultIt.next()); 82 | } 83 | 84 | 85 | @Test 86 | public void replaceRunners() throws IOException 87 | { 88 | BackupScorer target = new BackupScorer(); 89 | List original = new LinkedList<>(runners); 90 | target.replaceRunners(original, replacementRunners); 91 | 92 | Assert.assertEquals(4, original.size()); 93 | Assert.assertEquals(271, original.stream().filter(q->q.index == 0).findFirst().get().result, 1e-4); 94 | Assert.assertEquals(3, original.stream().filter(q->q.index == 1).findFirst().get().result, 1e-4); 95 | Assert.assertEquals(271, original.stream().filter(q->q.index == 2).findFirst().get().result, 1e-4); 96 | Assert.assertEquals(3, original.stream().filter(q->q.index == 3).findFirst().get().result, 1e-4); 97 | } 98 | } 99 | 100 | 101 | 102 | -------------------------------------------------------------------------------- /knowledge-graph/src/test/java/com/careerbuilder/search/relevancy/scoring/NodeScorerTest.java: -------------------------------------------------------------------------------- 1 | package com.careerbuilder.search.relevancy.scoring; 2 | 3 | import com.careerbuilder.search.relevancy.model.KnowledgeGraphRequest; 4 | import com.careerbuilder.search.relevancy.model.RequestNode; 5 | import com.careerbuilder.search.relevancy.model.ResponseNode; 6 | import com.careerbuilder.search.relevancy.model.ResponseValue; 7 | import com.careerbuilder.search.relevancy.NodeContext; 8 | import com.careerbuilder.search.relevancy.waitable.QueryWaitable; 9 | import mockit.Deencapsulation; 10 | import mockit.Mocked; 11 | import mockit.NonStrictExpectations; 12 | import mockit.integration.junit4.JMockit; 13 | import org.apache.solr.search.DocSet; 14 | import org.junit.Assert; 15 | import org.junit.Before; 16 | import org.junit.Test; 17 | import org.junit.runner.RunWith; 18 | 19 | import java.io.IOException; 20 | import java.util.Arrays; 21 | import java.util.LinkedList; 22 | import java.util.List; 23 | 24 | @RunWith(JMockit.class) 25 | public class NodeScorerTest { 26 | 27 | QueryWaitable[] fgRunners = new QueryWaitable[2]; 28 | QueryWaitable[] bgRunners = new QueryWaitable[2]; 29 | QueryWaitable[] qRunners = new QueryWaitable[2]; 30 | ResponseNode response = new ResponseNode(); 31 | ResponseNode pResponse = new ResponseNode(); 32 | RequestNode request = new RequestNode(); 33 | NodeContext context = new NodeContext(new KnowledgeGraphRequest()); 34 | List runners = new LinkedList<>(); 35 | @Mocked DocSet fgDomain; 36 | @Mocked DocSet bgDomain; 37 | @Mocked ScoreNormalizer normalizer; 38 | 39 | @Before 40 | public void init() { 41 | response.type = "keywords.v1"; 42 | response.values = new ResponseValue[0]; 43 | fgRunners[0] = new QueryWaitable(null, null, null, QueryWaitable.QueryType.FG, 0); 44 | fgRunners[1] = new QueryWaitable(null, null, null, QueryWaitable.QueryType.FG, 1); 45 | bgRunners[0] = new QueryWaitable(null, null, null, QueryWaitable.QueryType.BG, 0); 46 | bgRunners[1] = new QueryWaitable(null, null, null, QueryWaitable.QueryType.BG, 1); 47 | qRunners[0] = new QueryWaitable(null, null, null, QueryWaitable.QueryType.Q, 0); 48 | qRunners[1] = new QueryWaitable(null, null, null, QueryWaitable.QueryType.Q, 1); 49 | fgRunners[0].result = 0; 50 | fgRunners[1].result = 1; 51 | bgRunners[0].result = 0; 52 | bgRunners[1].result = 1; 53 | qRunners[0].result = 0; 54 | qRunners[1].result = 1; 55 | 56 | request.limit = 2; 57 | 58 | runners.addAll(Arrays.asList(fgRunners)); 59 | runners.addAll(Arrays.asList(bgRunners)); 60 | 61 | context.bgDomain = bgDomain; 62 | context.fgDomain = fgDomain; 63 | 64 | new NonStrictExpectations(){{ 65 | ScoreNormalizer.normalize((NodeContext) any, (ResponseValue[]) any); 66 | fgDomain.size(); result = 100; 67 | bgDomain.size(); result = 1000; 68 | }}; 69 | 70 | } 71 | 72 | @Test 73 | public void buildResponse() throws IOException 74 | { 75 | response.values = new ResponseValue[2]; 76 | response.values[0] = new ResponseValue("test"); 77 | response.values[1] = new ResponseValue("test"); 78 | NodeScorer target = new NodeScorer(); 79 | Deencapsulation.invoke(target, "addQueryResults", response, runners); 80 | 81 | Assert.assertEquals(0, response.values[0].foreground_popularity, 1e-4); 82 | Assert.assertEquals(0, response.values[0].background_popularity, 1e-4); 83 | Assert.assertEquals(1, response.values[1].foreground_popularity, 1e-4); 84 | Assert.assertEquals(1, response.values[1].background_popularity, 1e-4); 85 | 86 | } 87 | 88 | @Test 89 | public void processResponse() 90 | { 91 | pResponse.values = new ResponseValue[2]; 92 | pResponse.values[0] = new ResponseValue("test1"); 93 | pResponse.values[0].popularity= 50; 94 | pResponse.values[0].foreground_popularity = 50; 95 | pResponse.values[0].background_popularity = 500; 96 | pResponse.values[1] = new ResponseValue("test2"); 97 | pResponse.values[1].popularity= 50; 98 | pResponse.values[1].foreground_popularity = 50; 99 | pResponse.values[1].background_popularity = 500; 100 | NodeScorer target = new NodeScorer(); 101 | Deencapsulation.invoke(target, "processResponse", context, pResponse, request); 102 | 103 | Assert.assertEquals(0, pResponse.values[0].relatedness, 1e-4); 104 | Assert.assertEquals(0, pResponse.values[1].relatedness, 1e-4); 105 | } 106 | 107 | 108 | } 109 | -------------------------------------------------------------------------------- /knowledge-graph/src/test/java/com/careerbuilder/search/relevancy/scoring/QueryWaitableFactoryTest.java: -------------------------------------------------------------------------------- 1 | package com.careerbuilder.search.relevancy.scoring; 2 | 3 | import com.careerbuilder.search.relevancy.model.KnowledgeGraphRequest; 4 | import com.careerbuilder.search.relevancy.model.ResponseNode; 5 | import com.careerbuilder.search.relevancy.model.ResponseValue; 6 | import com.careerbuilder.search.relevancy.NodeContext; 7 | import com.careerbuilder.search.relevancy.waitable.QueryWaitable; 8 | import com.careerbuilder.search.relevancy.utility.ParseUtility; 9 | import mockit.*; 10 | import mockit.integration.junit4.JMockit; 11 | import org.apache.lucene.index.Term; 12 | import org.apache.lucene.search.Query; 13 | import org.apache.lucene.search.TermQuery; 14 | import org.apache.solr.common.params.SolrParams; 15 | import org.apache.solr.request.SolrQueryRequest; 16 | import org.apache.solr.search.DocSet; 17 | import org.apache.solr.search.SolrIndexSearcher; 18 | import org.junit.Assert; 19 | import org.junit.Before; 20 | import org.junit.Test; 21 | import org.junit.runner.RunWith; 22 | 23 | import java.io.IOException; 24 | import java.util.HashSet; 25 | import java.util.List; 26 | 27 | @RunWith(JMockit.class) 28 | public class QueryWaitableFactoryTest 29 | { 30 | 31 | @Mocked 32 | DocSet domain; 33 | NodeContext context = new NodeContext(new KnowledgeGraphRequest()); 34 | ResponseNode node; 35 | @Mocked 36 | SolrIndexSearcher unusedSearcher; 37 | @Mocked 38 | SolrQueryRequest unused; 39 | @Mocked 40 | SolrParams defTypeMap; 41 | 42 | @Before 43 | public void init() 44 | { 45 | unused.setParams(defTypeMap); 46 | context.req = unused; 47 | 48 | new MockUp() 49 | { 50 | @Mock 51 | public Query parseQueryString(String query, SolrQueryRequest req) 52 | { 53 | return new TermQuery(new Term("test",query)); 54 | } 55 | }; 56 | 57 | new ParseUtility(); 58 | new NonStrictExpectations() {{ 59 | unused.getSearcher(); returns(unusedSearcher); 60 | }}; 61 | 62 | ResponseValue[] values = new ResponseValue[4]; 63 | values[0] = new ResponseValue("v0"); 64 | values[1] = new ResponseValue("v1"); 65 | values[2] = new ResponseValue("v2"); 66 | values[3] = new ResponseValue("v3"); 67 | 68 | node = new ResponseNode("testType"); 69 | node.values = values; 70 | } 71 | 72 | @Test 73 | public void getQueryRunners() throws IOException 74 | { 75 | QueryRunnerFactory target = new QueryRunnerFactory(context, node, null); 76 | List actual = target.getQueryRunners(domain, "testField", QueryWaitable.QueryType.FG); 77 | 78 | Assert.assertEquals(4, actual.size()); 79 | 80 | Assert.assertEquals("test:testField:\"v0\"",((Query)Deencapsulation.getField(actual.get(0), "query")).toString()); 81 | Assert.assertEquals("test:testField:\"v1\"",((Query)Deencapsulation.getField(actual.get(1), "query")).toString()); 82 | Assert.assertEquals("test:testField:\"v2\"",((Query)Deencapsulation.getField(actual.get(2), "query")).toString()); 83 | Assert.assertEquals("test:testField:\"v3\"",((Query)Deencapsulation.getField(actual.get(3), "query")).toString()); 84 | 85 | Assert.assertEquals(QueryWaitable.QueryType.FG, actual.get(0).type); 86 | Assert.assertEquals(QueryWaitable.QueryType.FG, actual.get(1).type); 87 | Assert.assertEquals(QueryWaitable.QueryType.FG, actual.get(2).type); 88 | Assert.assertEquals(QueryWaitable.QueryType.FG, actual.get(3).type); 89 | 90 | Assert.assertEquals(0, actual.get(0).index); 91 | Assert.assertEquals(1, actual.get(1).index); 92 | Assert.assertEquals(2, actual.get(2).index); 93 | Assert.assertEquals(3, actual.get(3).index); 94 | } 95 | 96 | @Test 97 | public void getQueryRunnersFallback() throws IOException 98 | { 99 | HashSet fallback = new HashSet<>(); 100 | fallback.add(1); 101 | QueryRunnerFactory target = new QueryRunnerFactory(context, node, fallback); 102 | List actual = target.getQueryRunners(domain, "testField", QueryWaitable.QueryType.FG); 103 | 104 | Assert.assertEquals(1, actual.size()); 105 | Assert.assertEquals("test:testField:\"v1\"",((Query)Deencapsulation.getField(actual.get(0), "query")).toString()); 106 | Assert.assertEquals(QueryWaitable.QueryType.FG, actual.get(0).type); 107 | Assert.assertEquals(1, actual.get(0).index); 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /knowledge-graph/src/test/java/com/careerbuilder/search/relevancy/scoring/RelatednessStrategyTest.java: -------------------------------------------------------------------------------- 1 | package com.careerbuilder.search.relevancy.scoring; 2 | 3 | import org.junit.Assert; 4 | import org.junit.Before; 5 | import org.junit.Test; 6 | 7 | public class RelatednessStrategyTest { 8 | 9 | @Before 10 | public void init() 11 | { 12 | } 13 | 14 | @Test 15 | public void z_mean() 16 | { 17 | double expected = 0; 18 | double actual = BinomialStrategy.score(50, 100, 25, 50); 19 | 20 | Assert.assertEquals(expected, actual, 1e-4); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /knowledge-graph/src/test/java/com/careerbuilder/search/relevancy/scoring/ScoreNormalizerTest.java: -------------------------------------------------------------------------------- 1 | package com.careerbuilder.search.relevancy.scoring; 2 | 3 | import com.careerbuilder.search.relevancy.model.ResponseValue; 4 | import mockit.Deencapsulation; 5 | import mockit.integration.junit4.JMockit; 6 | import org.junit.Assert; 7 | import org.junit.Test; 8 | import org.junit.runner.RunWith; 9 | 10 | import static junit.framework.TestCase.assertEquals; 11 | 12 | @RunWith(JMockit.class) 13 | public class ScoreNormalizerTest { 14 | 15 | @Test 16 | public void normalizeValues() 17 | { 18 | ResponseValue one = new ResponseValue("test"); 19 | one.popularity = 1; 20 | one.foreground_popularity=1; 21 | one.background_popularity=1; 22 | 23 | ResponseValue two = new ResponseValue("test"); 24 | two.popularity=2; 25 | two.foreground_popularity=2; 26 | two.background_popularity=2; 27 | 28 | ResponseValue [] values = new ResponseValue[] { one, two }; 29 | 30 | Deencapsulation.invoke(ScoreNormalizer.class, "normalizeValues", (int)10, values); 31 | 32 | Assert.assertEquals(100000, values[0].popularity, 1e-4); 33 | Assert.assertEquals(100000, values[0].background_popularity, 1e-4); 34 | Assert.assertEquals(100000, values[0].foreground_popularity, 1e-4); 35 | Assert.assertEquals(200000, values[1].popularity, 1e-4); 36 | Assert.assertEquals(200000, values[1].background_popularity, 1e-4); 37 | Assert.assertEquals(200000, values[1].foreground_popularity, 1e-4); 38 | 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /knowledge-graph/src/test/java/com/careerbuilder/search/relevancy/threadpool/MapUtilityTest.java: -------------------------------------------------------------------------------- 1 | package com.careerbuilder.search.relevancy.threadpool; 2 | 3 | import com.careerbuilder.search.relevancy.utility.MapUtility; 4 | import org.apache.solr.common.util.SimpleOrderedMap; 5 | import org.junit.Assert; 6 | import org.junit.Before; 7 | import org.junit.Test; 8 | 9 | public class MapUtilityTest { 10 | 11 | 12 | @Before 13 | public void init() { 14 | } 15 | 16 | @Test 17 | public void mapContainsValue() 18 | { 19 | SimpleOrderedMap map = new SimpleOrderedMap<>(); 20 | map.add("id", "123"); 21 | map.add("name", "testName"); 22 | 23 | Assert.assertTrue(MapUtility.mapContainsValue("123", map)); 24 | Assert.assertFalse(MapUtility.mapContainsValue("12", map)); 25 | Assert.assertTrue(MapUtility.mapContainsValue("testName", map)); 26 | Assert.assertFalse(MapUtility.mapContainsValue("test", map)); 27 | } 28 | 29 | @Test public void mapsEqual() { 30 | SimpleOrderedMap map1 = new SimpleOrderedMap<>(); 31 | map1.add("id", "123"); 32 | map1.add("name", "testName"); 33 | SimpleOrderedMap map2 = new SimpleOrderedMap<>(); 34 | map2.add("id", "123"); 35 | map2.add("name", "testName"); 36 | 37 | Assert.assertTrue(MapUtility.mapsEqual(map1, map2)); 38 | } 39 | 40 | @Test public void mapsEqual_NotEqual() { 41 | SimpleOrderedMap map1 = new SimpleOrderedMap<>(); 42 | map1.add("id", "123"); 43 | map1.add("name", "testName"); 44 | SimpleOrderedMap map2 = new SimpleOrderedMap<>(); 45 | map2.add("id", "321"); 46 | map2.add("name", "testName"); 47 | SimpleOrderedMap emptyMap = new SimpleOrderedMap<>(); 48 | 49 | Assert.assertFalse(MapUtility.mapsEqual(map1, map2)); 50 | Assert.assertFalse(MapUtility.mapsEqual(null, map2)); 51 | Assert.assertFalse(MapUtility.mapsEqual(map1, null)); 52 | Assert.assertFalse(MapUtility.mapsEqual(map1, emptyMap)); 53 | Assert.assertFalse(MapUtility.mapsEqual(emptyMap, map2)); 54 | } 55 | 56 | } 57 | -------------------------------------------------------------------------------- /knowledge-graph/src/test/java/com/careerbuilder/search/relevancy/threadpool/ThreadPoolTest.java: -------------------------------------------------------------------------------- 1 | package com.careerbuilder.search.relevancy.threadpool; 2 | 3 | import com.careerbuilder.search.relevancy.waitable.Waitable; 4 | import mockit.integration.junit4.JMockit; 5 | import org.junit.Assert; 6 | import org.junit.Before; 7 | import org.junit.Test; 8 | import org.junit.runner.RunWith; 9 | 10 | import java.io.IOException; 11 | import java.util.List; 12 | import java.util.concurrent.Callable; 13 | import java.util.concurrent.Future; 14 | 15 | @RunWith(JMockit.class) 16 | public class ThreadPoolTest { 17 | 18 | public class Dummy extends Waitable implements Callable{ 19 | public int result; 20 | public Waitable call() 21 | { 22 | result = 1; 23 | return this; 24 | } 25 | } 26 | Dummy [] dummyRunners = new Dummy[4]; 27 | 28 | @Before 29 | public void init() { 30 | for(int i =0; i < dummyRunners.length; ++i) 31 | { 32 | dummyRunners[i] = new Dummy(); 33 | } 34 | } 35 | 36 | @Test(timeout=10000) 37 | public void multiplex_demultiplex() throws IOException 38 | { 39 | List> futures = ThreadPool.getInstance().multiplex(dummyRunners); 40 | ThreadPool.getInstance().demultiplex(futures); 41 | 42 | Assert.assertTrue(true); 43 | for(int i = 0; i < dummyRunners.length; ++i) 44 | { 45 | Assert.assertEquals(1, dummyRunners[i].result); 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /knowledge-graph/src/test/java/com/careerbuilder/search/relevancy/utility/ResponseUtilityTest.java: -------------------------------------------------------------------------------- 1 | package com.careerbuilder.search.relevancy.utility; 2 | 3 | import com.careerbuilder.search.relevancy.model.ResponseNode; 4 | import com.careerbuilder.search.relevancy.model.ResponseValue; 5 | import com.careerbuilder.search.relevancy.model.SortType; 6 | import org.junit.Assert; 7 | import org.junit.Before; 8 | import org.junit.Test; 9 | 10 | import java.util.Arrays; 11 | import java.util.LinkedList; 12 | import java.util.List; 13 | 14 | import static junit.framework.TestCase.assertEquals; 15 | 16 | public class ResponseUtilityTest { 17 | 18 | private ResponseNode nodeWithDups; 19 | private List valuesDups; 20 | private List values; 21 | private ResponseNode node; 22 | private String [] requestValuesDups = new String [] { "v1", "v1", "v3", "V3", "V3", "v4"}; 23 | 24 | @Before 25 | public void init() 26 | { 27 | nodeWithDups = new ResponseNode(); 28 | node = new ResponseNode(); 29 | ResponseValue v1 = new ResponseValue("v1", 0.75); 30 | ResponseValue v2 = new ResponseValue("v2", 0.5); 31 | ResponseValue v3 = new ResponseValue("v3", 0.25); 32 | ResponseValue v4 = new ResponseValue("v4", 0); 33 | v1.background_popularity=1; 34 | v1.popularity=1; 35 | v2.background_popularity=1; 36 | v2.popularity=0; 37 | v3.background_popularity=0; 38 | v3.popularity=2; 39 | v4.background_popularity=1; 40 | v4.popularity=1; 41 | valuesDups = new LinkedList<>(); 42 | valuesDups.add(v4); 43 | valuesDups.add(v3); 44 | valuesDups.add(v2); 45 | valuesDups.add(v2); 46 | valuesDups.add(v2); 47 | valuesDups.add(v1); 48 | valuesDups.add(v1); 49 | values = new LinkedList<>(); 50 | values.add(v1); 51 | values.add(v2); 52 | values.add(v3); 53 | values.add(v4); 54 | } 55 | 56 | @Test 57 | public void distinct_Request() 58 | { 59 | String [] expected = new String[] {"v1", "v3", "v4"}; 60 | List actual = ResponseUtility.distinct(requestValuesDups); 61 | 62 | Assert.assertArrayEquals(expected, actual.toArray(new String[0])); 63 | } 64 | 65 | @Test 66 | public void distinct() 67 | { 68 | SortUtility.sortResponseValues(valuesDups, SortType.foreground_popularity); 69 | ResponseUtility.distinct(valuesDups); 70 | 71 | assertEquals(4, valuesDups.size()); 72 | assertEquals("v1", valuesDups.get(0).value); 73 | assertEquals("v2", valuesDups.get(1).value); 74 | assertEquals("v3", valuesDups.get(2).value); 75 | assertEquals("v4", valuesDups.get(3).value); 76 | } 77 | 78 | @Test 79 | public void filterMergeKeep() 80 | { 81 | List keep = Arrays.asList(new String [] {"v4"}); 82 | 83 | List actual = ResponseUtility.filterMergeResults(values, keep, 2, SortType.foreground_popularity); 84 | 85 | assertEquals(2, actual.size()); 86 | assertEquals("v1", actual.get(0).value); 87 | assertEquals("v4", actual.get(1).value); 88 | } 89 | 90 | @Test 91 | public void filterMerge_noKeep() 92 | { 93 | List keep = new LinkedList<>(); 94 | 95 | List actual = ResponseUtility.filterMergeResults(values, keep, 2, SortType.foreground_popularity); 96 | 97 | assertEquals(2, actual.size()); 98 | assertEquals("v1", actual.get(0).value); 99 | assertEquals("v2", actual.get(1).value); 100 | } 101 | 102 | @Test 103 | public void filterMergeOnlyKeep() 104 | { 105 | List keep = Arrays.asList(new String [] { "v3", "v4", "v2"}); 106 | 107 | List actual = ResponseUtility.filterMergeResults(values, keep, 2, SortType.foreground_popularity); 108 | 109 | assertEquals(3, actual.size()); 110 | assertEquals("v2", actual.get(0).value); 111 | assertEquals("v3", actual.get(1).value); 112 | assertEquals("v4", actual.get(2).value); 113 | } 114 | 115 | @Test(expected= IllegalArgumentException.class) 116 | public void filterMergeException() 117 | { 118 | List keep = Arrays.asList(new String[]{"v3", "v4", "v2", "v2", "v2"}); 119 | 120 | List actual = ResponseUtility.filterMergeResults(values, keep, 2, SortType.foreground_popularity); 121 | } 122 | 123 | public void thresholdMinPopularityNoFilter() 124 | { 125 | List actual = ResponseUtility.thresholdMinPop(values, 0); 126 | 127 | assertEquals(4, actual.size()); 128 | assertEquals("v1", actual.get(0).value); 129 | assertEquals("v2", actual.get(1).value); 130 | assertEquals("v3", actual.get(2).value); 131 | assertEquals("v4", actual.get(3).value); 132 | } 133 | 134 | public void thresholdMinPopularityFilter() 135 | { 136 | List actual = ResponseUtility.thresholdMinPop(values, 1); 137 | 138 | assertEquals(1, actual.size()); 139 | assertEquals("v1", actual.get(0).value); 140 | } 141 | 142 | public void thresholdMinPopularityFilterNoReturn() 143 | { 144 | List actual = ResponseUtility.thresholdMinFGBGPop(values, 1); 145 | 146 | assertEquals(1, actual.size()); 147 | assertEquals("v1", actual.get(0).value); 148 | assertEquals("v2", actual.get(1).value); 149 | } 150 | } 151 | -------------------------------------------------------------------------------- /knowledge-graph/src/test/java/com/careerbuilder/search/relevancy/waitable/AggregationWaitableTest.java: -------------------------------------------------------------------------------- 1 | package com.careerbuilder.search.relevancy.waitable; 2 | 3 | import com.careerbuilder.search.relevancy.generation.FacetFieldAdapter; 4 | import com.careerbuilder.search.relevancy.model.RequestNode; 5 | import com.careerbuilder.search.relevancy.model.ResponseValue; 6 | import com.careerbuilder.search.relevancy.NodeContext; 7 | import com.google.gson.Gson; 8 | import mockit.*; 9 | import mockit.integration.junit4.JMockit; 10 | import org.apache.lucene.index.Term; 11 | import org.apache.lucene.search.Query; 12 | import org.apache.lucene.search.TermQuery; 13 | import org.apache.solr.common.params.FacetParams; 14 | import org.apache.solr.common.params.MapSolrParams; 15 | import org.apache.solr.common.util.SimpleOrderedMap; 16 | import org.apache.solr.response.SolrQueryResponse; 17 | import org.junit.Assert; 18 | import org.junit.Before; 19 | import org.junit.Test; 20 | import org.junit.runner.RunWith; 21 | 22 | import java.util.LinkedList; 23 | import java.util.Map; 24 | 25 | @RunWith(JMockit.class) 26 | public class AggregationWaitableTest 27 | { 28 | 29 | NodeContext context; 30 | RequestNode request; 31 | String field; 32 | Gson gson; 33 | @Mocked 34 | FacetFieldAdapter adapter; 35 | 36 | @Before 37 | public void init() 38 | { 39 | context = new NodeContext(); 40 | gson = new Gson(); 41 | LinkedList queries = new LinkedList<>(); 42 | queries.add(new TermQuery(new Term("testField1", "testQuery1"))); 43 | queries.add(new TermQuery(new Term("testField2", "testQuery2"))); 44 | Deencapsulation.setField(context, "fgQueries", queries); 45 | 46 | new MockUp(){ 47 | @Mock public void $init(NodeContext context, String field) {} 48 | }; 49 | 50 | request = new RequestNode(); 51 | request.limit = 1; 52 | field = "testField1"; 53 | } 54 | @Test 55 | public void parseResponse() { 56 | SolrQueryResponse resp = new SolrQueryResponse(); 57 | SimpleOrderedMap root = new SimpleOrderedMap<>(); 58 | SimpleOrderedMap queryFacet= new SimpleOrderedMap<>(); 59 | SimpleOrderedMap fieldFacet= new SimpleOrderedMap<>(); 60 | LinkedList buckets = new LinkedList<>(); 61 | SimpleOrderedMap bucket1 = new SimpleOrderedMap<>(); 62 | SimpleOrderedMap bucket2 = new SimpleOrderedMap<>(); 63 | bucket1.add("val", "testValue1"); 64 | bucket1.add("count", 1234); 65 | bucket2.add("val", "testValue2"); 66 | bucket2.add("count", 4321); 67 | buckets.add(bucket1); 68 | buckets.add(bucket2); 69 | fieldFacet.add("buckets", buckets); 70 | queryFacet.add(AggregationWaitable.FIELD_FACET_NAME, fieldFacet); 71 | root.add(AggregationWaitable.QUERY_FACET_NAME, queryFacet); 72 | resp.add("facets", root); 73 | 74 | LinkedList expected = new LinkedList<>(); 75 | expected.add(new ResponseValue("testValue1", 1234)); 76 | expected.add(new ResponseValue("testValue2", 4321)); 77 | 78 | 79 | AggregationWaitable target = new AggregationWaitable(context, adapter, "query", "testfield", 0, 0); 80 | 81 | Deencapsulation.invoke(target, "parseResponse", resp); 82 | 83 | Assert.assertEquals(expected.size(), target.buckets.size()); 84 | for(int i = 0; i < target.buckets.size(); ++i) 85 | { 86 | Assert.assertEquals(buckets.get(i), target.buckets.get(i)); 87 | } 88 | } 89 | 90 | @Test 91 | public void buildFacetParams(){ 92 | AggregationWaitable target = new AggregationWaitable(context, adapter, "query", "testField",0, 0); 93 | 94 | MapSolrParams actual = Deencapsulation.invoke(target, "buildFacetParams"); 95 | 96 | Assert.assertEquals("json".compareTo(actual.get("wt")), 0); 97 | Assert.assertEquals("1".compareTo(actual.get("facet.version")), 0); 98 | Assert.assertEquals("true".compareTo(actual.get(FacetParams.FACET)), 0); 99 | } 100 | 101 | @Test 102 | public void buildFacetJson(){ 103 | AggregationWaitable target = new AggregationWaitable(context, adapter, "query", "testfield", 0, 0); 104 | int limit = Math.max(request.limit, 25)*5; 105 | String expected = "{\"facet\":{\"queryFacet\":{\"query\":{\"facet\":{\"fieldFacet\":{\"field\":" + 106 | "{\"type\":\"field\",\"field\":\"testfield\",\"limit\":"+limit+"}}},\"q\":\"query\"}}}}"; 107 | 108 | Map actual = Deencapsulation.invoke(target, "buildFacetJson"); 109 | String actualStr = gson.toJson(actual); 110 | Assert.assertEquals(expected, actualStr); 111 | } 112 | 113 | } 114 | -------------------------------------------------------------------------------- /knowledge-graph/src/test/java/com/careerbuilder/search/relevancy/waitable/QueryWaitableTest.java: -------------------------------------------------------------------------------- 1 | package com.careerbuilder.search.relevancy.waitable; 2 | 3 | import com.careerbuilder.search.relevancy.NodeContext; 4 | import mockit.Expectations; 5 | import mockit.Mocked; 6 | import mockit.integration.junit4.JMockit; 7 | import org.apache.lucene.index.Term; 8 | import org.apache.lucene.search.Query; 9 | import org.apache.lucene.search.TermQuery; 10 | import org.apache.solr.search.DocSet; 11 | import org.apache.solr.search.SolrIndexSearcher; 12 | import org.junit.Assert; 13 | import org.junit.Before; 14 | import org.junit.Test; 15 | import org.junit.runner.RunWith; 16 | 17 | import java.io.IOException; 18 | 19 | @RunWith(JMockit.class) 20 | public class QueryWaitableTest 21 | { 22 | 23 | NodeContext context; 24 | @Mocked SolrIndexSearcher searcher; 25 | @Mocked DocSet docSet; 26 | Query query; 27 | 28 | @Before 29 | public void init() throws IOException 30 | { 31 | context = new NodeContext(); 32 | query = new TermQuery(new Term("testField1", "testQuery1")); 33 | 34 | new Expectations() {{ 35 | searcher.numDocs(query, docSet); returns(1); 36 | }}; 37 | } 38 | 39 | @Test 40 | public void call(){ 41 | QueryWaitable target = new QueryWaitable(searcher, query, docSet, QueryWaitable.QueryType.FG, 1); 42 | 43 | target.call(); 44 | 45 | Assert.assertEquals(1, target.result); 46 | Assert.assertEquals(QueryWaitable.QueryType.FG, target.type); 47 | Assert.assertEquals(1, target.index); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /patches/lucene_solr_5_1_0.patch: -------------------------------------------------------------------------------- 1 | From faab4251e164057acec0b7c7e457490a084edec7 Mon Sep 17 00:00:00 2001 2 | From: andhesmi 3 | Date: Wed, 6 Jan 2016 16:25:06 -0500 4 | Subject: [PATCH] fixing Facet Field leak and setting custom jetty.xml 5 | 6 | --- 7 | solr/core/src/java/org/apache/solr/search/facet/FacetField.java | 2 +- 8 | solr/server/etc/jetty.xml | 2 +- 9 | 2 files changed, 2 insertions(+), 2 deletions(-) 10 | 11 | diff --git a/solr/core/src/java/org/apache/solr/search/facet/FacetField.java b/solr/core/src/java/org/apache/solr/search/facet/FacetField.java 12 | index 7c13f77..6be438f 100644 13 | --- a/solr/core/src/java/org/apache/solr/search/facet/FacetField.java 14 | +++ b/solr/core/src/java/org/apache/solr/search/facet/FacetField.java 15 | @@ -341,7 +341,7 @@ abstract class FacetFieldProcessorFCBase extends FacetFieldProcessor { 16 | // handle sub-facets for this bucket 17 | if (freq.getSubFacets().size() > 0) { 18 | FacetContext subContext = fcontext.sub(); 19 | - subContext.base = fcontext.searcher.getDocSet(new TermQuery(new Term(sf.getName(), br.clone())), fcontext.base); 20 | + subContext.base = fcontext.searcher.getDocSet(new TermQuery(new Term(sf.getName(), BytesRef.deepCopyOf(br))), fcontext.base); 21 | try { 22 | fillBucketSubs(bucket, subContext); 23 | } finally { 24 | diff --git a/solr/server/etc/jetty.xml b/solr/server/etc/jetty.xml 25 | index 3b1abee..20596f1 100644 26 | --- a/solr/server/etc/jetty.xml 27 | +++ b/solr/server/etc/jetty.xml 28 | @@ -19,7 +19,7 @@ 29 | 30 | 31 | 10 32 | - 10000 33 | + 100 34 | false 35 | 36 | 37 | -- 38 | 2.4.9 (Apple Git-60) 39 | 40 | -------------------------------------------------------------------------------- /rebuild.sh: -------------------------------------------------------------------------------- 1 | cd knowledge-graph/ 2 | mvn clean 3 | mvn package 4 | cd ../ 5 | ant package-nobuild 6 | cd deploy 7 | chmod +x restart-solr.sh 8 | chmod +x restart-solr-dbg.sh 9 | chmod +x solr/bin/solr 10 | ./restart-solr-dbg.sh 11 | 12 | --------------------------------------------------------------------------------