├── lookup ├── .dockerignore ├── Dockerfile ├── src │ └── main │ │ ├── java │ │ └── org │ │ │ └── dbpedia │ │ │ └── lookup │ │ │ ├── config │ │ │ ├── IndexMode.java │ │ │ ├── IndexField.java │ │ │ ├── LookupField.java │ │ │ ├── QuerySettings.java │ │ │ ├── IndexConfig.java │ │ │ └── LookupConfig.java │ │ │ ├── RDFFileFilter.java │ │ │ ├── indexer │ │ │ ├── UriAnalyzer.java │ │ │ ├── StringPhraseAnalyzer.java │ │ │ ├── NGramAnalyzer.java │ │ │ ├── LuceneIndexWriter.java │ │ │ └── LookupIndexer.java │ │ │ ├── Constants.java │ │ │ ├── RequestUtils.java │ │ │ ├── server │ │ │ ├── LookupIndexerServlet.java │ │ │ └── LookupSearcherServlet.java │ │ │ ├── DatabusUtils.java │ │ │ ├── Main.java │ │ │ └── searcher │ │ │ └── LookupSearcher.java │ │ └── resources │ │ └── logback.xml └── pom.xml ├── .vscode ├── settings.json └── launch.json ├── docker-compose.yml ├── examples ├── indexing │ ├── ontology-file-indexer.yml │ ├── dbpedia-resource-indexer.yml │ ├── ontology-collection-indexer.yml │ ├── dbpedia-resource-indexer-file.yml │ └── dbpedia-ontology-collection-indexer.yml ├── config.yml └── index.html ├── .gitignore ├── README.md ├── doc ├── indexing.md └── server.md └── LICENSE /lookup/.dockerignore: -------------------------------------------------------------------------------- 1 | */target 2 | .git 3 | .gitignore 4 | */test 5 | */index 6 | */logs -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "java.configuration.updateBuildConfiguration": "automatic", 3 | "java.debug.settings.onBuildFailureProceed": true 4 | } -------------------------------------------------------------------------------- /lookup/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM openjdk:latest 2 | EXPOSE 8082 3 | COPY ./target/lookup-1.0-jar-with-dependencies.jar /opt/app/ 4 | CMD [ "java","-jar","/opt/app/lookup-1.0-jar-with-dependencies.jar", "-c", "/resources/config.yml" ] 5 | -------------------------------------------------------------------------------- /lookup/src/main/java/org/dbpedia/lookup/config/IndexMode.java: -------------------------------------------------------------------------------- 1 | package org.dbpedia.lookup.config; 2 | 3 | public enum IndexMode { 4 | INDEX_IN_MEMORY, 5 | BUILD_AND_INDEX_ON_DISK, 6 | INDEX_ON_DISK, 7 | INDEX_SPARQL_ENDPOINT, 8 | } -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: "3.0" 2 | services: 3 | lookup: 4 | image: "dbpedia/lookup:dev" 5 | build: ./lookup 6 | ports: 7 | - 8082:8082 8 | environment: 9 | CONFIG_PATH: /resources/config.yml 10 | volumes: 11 | - ./examples/:/resources/ 12 | -------------------------------------------------------------------------------- /examples/indexing/ontology-file-indexer.yml: -------------------------------------------------------------------------------- 1 | version: "1.0" 2 | indexMode: INDEX_IN_MEMORY 3 | dataPath: ./examples/indexing/data 4 | indexFields: 5 | - fieldName: label 6 | documentVariable: resource 7 | query: > 8 | SELECT ?resource ?label WHERE { 9 | { 10 | ?resource ?label . 11 | FILTER(lang(?label) = 'en') 12 | #VALUES# 13 | } 14 | } 15 | LIMIT 10000 -------------------------------------------------------------------------------- /examples/indexing/dbpedia-resource-indexer.yml: -------------------------------------------------------------------------------- 1 | version: "1.0" 2 | indexMode: INDEX_SPARQL_ENDPOINT 3 | sparqlEndpoint: https://dbpedia.org/sparql 4 | indexFields: 5 | - fieldName: label 6 | documentVariable: resource 7 | query: > 8 | SELECT ?resource ?label WHERE { 9 | { 10 | ?resource ?label . 11 | FILTER(lang(?label) = 'en') 12 | #VALUES# 13 | } 14 | } 15 | LIMIT 10000 -------------------------------------------------------------------------------- /examples/indexing/ontology-collection-indexer.yml: -------------------------------------------------------------------------------- 1 | version: "1.0" 2 | indexMode: INDEX_IN_MEMORY 3 | collectionUri: https://databus.dbpedia.org/janfo/collections/moss-ontologies 4 | indexFields: 5 | - fieldName: label 6 | documentVariable: resource 7 | query: > 8 | SELECT ?resource ?label WHERE { 9 | { 10 | ?resource ?label . 11 | FILTER(lang(?label) = 'en') 12 | #VALUES# 13 | } 14 | } 15 | LIMIT 10000 -------------------------------------------------------------------------------- /examples/indexing/dbpedia-resource-indexer-file.yml: -------------------------------------------------------------------------------- 1 | version: "1.0" 2 | indexMode: BUILD_AND_INDEX_ON_DISK 3 | collectionUri: https://databus.dbpedia.org/janfo/collections/lookup 4 | tdbPath: /resources/tdb 5 | indexFields: 6 | - fieldName: label 7 | documentVariable: resource 8 | query: > 9 | SELECT ?resource ?label WHERE { 10 | { 11 | ?resource ?label . 12 | FILTER(lang(?label) = 'de') 13 | #VALUES# 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /examples/indexing/dbpedia-ontology-collection-indexer.yml: -------------------------------------------------------------------------------- 1 | version: "1.0" 2 | indexMode: BUILD_AND_INDEX_ON_DISK 3 | collectionUri: https://databus.dbpedia.org/janfo/collections/lookup 4 | tdbPath: /resources/tdb 5 | indexFields: 6 | - fieldName: label 7 | documentVariable: resource 8 | query: > 9 | SELECT ?resource ?label WHERE { 10 | { 11 | ?resource ?label . 12 | FILTER(lang(?label) = 'de') 13 | #VALUES# 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // Use IntelliSense to learn about possible attributes. 3 | // Hover to view descriptions of existing attributes. 4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 5 | "version": "0.2.0", 6 | "configurations": [ 7 | { 8 | "type": "java", 9 | "name": "Launch Lookup Server", 10 | "request": "launch", 11 | "mainClass": "org.dbpedia.lookup.Main", 12 | "projectName": "lookup", 13 | "args": "-c C:/Users/janfo/Documents/Work/databus/search/servlet-config.yml" // ./examples/config.yml" 14 | } 15 | ] 16 | } -------------------------------------------------------------------------------- /lookup/src/main/java/org/dbpedia/lookup/RDFFileFilter.java: -------------------------------------------------------------------------------- 1 | package org.dbpedia.lookup; 2 | 3 | import java.io.File; 4 | import java.io.FileFilter; 5 | 6 | /** 7 | * File filter for RDF files. Only accepts files with well-known RDF format ending 8 | */ 9 | public class RDFFileFilter implements FileFilter { 10 | 11 | @Override 12 | public boolean accept(File pathname) { 13 | 14 | String fileName = pathname.getName(); 15 | 16 | boolean accept = false; 17 | 18 | accept |= fileName.contains(".ttl"); 19 | accept |= fileName.contains(".turtle"); 20 | accept |= fileName.contains(".n3"); 21 | accept |= fileName.contains(".nt"); 22 | 23 | return accept; 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /examples/config.yml: -------------------------------------------------------------------------------- 1 | version: "1.0" 2 | indexPath: ./index 3 | maxBufferedDocs: 1000000 4 | logInterval: 100 5 | exactMatchBoost: 10 6 | prefixMatchBoost: 7 7 | fuzzyMatchBoost: 1 8 | fuzzyEditDistance: 2 9 | fuzzyPrefixLength: 2 10 | maxResults: 10000 11 | format: JSON 12 | minScore: 0.1 13 | lookupFields: 14 | - name: label 15 | weight: 1 16 | highlight: true 17 | tokenize: true 18 | allowPartialMatch: true 19 | queryByDefault: true 20 | - name: comment 21 | weight: .2 22 | highlight: true 23 | tokenize: true 24 | allowPartialMatch: true 25 | queryByDefault: true 26 | - name: id 27 | weight: 10 28 | exact: true 29 | highlight: false 30 | tokenize: false 31 | queryByDefault: false -------------------------------------------------------------------------------- /lookup/src/main/java/org/dbpedia/lookup/indexer/UriAnalyzer.java: -------------------------------------------------------------------------------- 1 | package org.dbpedia.lookup.indexer; 2 | 3 | import org.apache.lucene.analysis.Analyzer; 4 | import org.apache.lucene.analysis.TokenFilter; 5 | import org.apache.lucene.analysis.core.KeywordTokenizer; 6 | import org.apache.lucene.analysis.miscellaneous.TrimFilter; 7 | 8 | /** 9 | * Analzyer setup for uris and other ids, only trims, no lowercase 10 | */ 11 | public class UriAnalyzer extends Analyzer { 12 | 13 | @Override 14 | protected TokenStreamComponents createComponents(String fieldName) { 15 | 16 | KeywordTokenizer tok = new KeywordTokenizer(); 17 | TokenFilter trimFilter = new TrimFilter(tok); 18 | 19 | return new TokenStreamComponents(tok, trimFilter); 20 | } 21 | } -------------------------------------------------------------------------------- /lookup/src/main/java/org/dbpedia/lookup/indexer/StringPhraseAnalyzer.java: -------------------------------------------------------------------------------- 1 | package org.dbpedia.lookup.indexer; 2 | 3 | import org.apache.lucene.analysis.Analyzer; 4 | import org.apache.lucene.analysis.LowerCaseFilter; 5 | import org.apache.lucene.analysis.TokenFilter; 6 | import org.apache.lucene.analysis.core.KeywordTokenizer; 7 | import org.apache.lucene.analysis.miscellaneous.TrimFilter; 8 | 9 | /** 10 | * Analzyer setup with lowercase and trim filter 11 | */ 12 | public class StringPhraseAnalyzer extends Analyzer { 13 | 14 | @Override 15 | protected TokenStreamComponents createComponents(String fieldName) { 16 | KeywordTokenizer tok = new KeywordTokenizer(); 17 | 18 | TokenFilter lowerCaseFilter = new LowerCaseFilter(tok); 19 | TokenFilter trimFilter = new TrimFilter(lowerCaseFilter); 20 | 21 | return new TokenStreamComponents(tok, trimFilter); 22 | } 23 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | *.class 3 | 4 | # Mobile Tools for Java (J2ME) 5 | .mtj.tmp/ 6 | 7 | # Package Files # 8 | *.jar 9 | *.war 10 | *.ear 11 | 12 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 13 | hs_err_pid* 14 | 15 | # netbeans 16 | nbproject/private/ 17 | build/ 18 | nbbuild/ 19 | 20 | # the dist file could make some problems 21 | # dist/ 22 | nbdist/ 23 | nbactions.xml 24 | nb-configuration.xml 25 | .nb-gradle/ 26 | 27 | # Eclipse 28 | .classpath 29 | .project 30 | .settings/ 31 | 32 | # Intellij 33 | .idea/ 34 | *.iml 35 | *.iws 36 | 37 | # Mac 38 | .DS_Store 39 | 40 | # Maven 41 | log/ 42 | target/ 43 | pom.xml.tag 44 | pom.xml.releaseBackup 45 | pom.xml.versionsBackup 46 | pom.xml.next 47 | release.properties 48 | dependency-reduced-pom.xml 49 | 50 | # Application 51 | lookup-index/ 52 | /bin/ 53 | WebContent 54 | lucene-index 55 | tb-graph 56 | index 57 | logs 58 | tdb -------------------------------------------------------------------------------- /lookup/src/main/java/org/dbpedia/lookup/config/IndexField.java: -------------------------------------------------------------------------------- 1 | package org.dbpedia.lookup.config; 2 | 3 | public class IndexField { 4 | 5 | private String fieldName; 6 | 7 | private String documentVariable; 8 | 9 | private String query; 10 | 11 | private String type; 12 | 13 | public String getFieldName() { 14 | return fieldName; 15 | } 16 | 17 | public void setFieldName(String fieldName) { 18 | this.fieldName = fieldName; 19 | } 20 | 21 | public String getDocumentVariable() { 22 | return documentVariable; 23 | } 24 | 25 | public void setDocumentVariable(String documentVariable) { 26 | this.documentVariable = documentVariable; 27 | } 28 | 29 | public String getQuery() { 30 | return query; 31 | } 32 | 33 | public void setQuery(String query) { 34 | this.query = query; 35 | } 36 | 37 | public String getType() { 38 | return type; 39 | } 40 | 41 | public void setType(String type) { 42 | this.type = type; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /lookup/src/main/java/org/dbpedia/lookup/indexer/NGramAnalyzer.java: -------------------------------------------------------------------------------- 1 | package org.dbpedia.lookup.indexer; 2 | 3 | import org.apache.lucene.analysis.Analyzer; 4 | import org.apache.lucene.analysis.LowerCaseFilter; 5 | import org.apache.lucene.analysis.Tokenizer; 6 | import org.apache.lucene.analysis.TokenStream; 7 | import org.apache.lucene.analysis.en.PorterStemFilter; 8 | import org.apache.lucene.analysis.miscellaneous.TrimFilter; 9 | import org.apache.lucene.analysis.ngram.NGramTokenFilter; 10 | import org.apache.lucene.analysis.classic.ClassicFilter; 11 | import org.apache.lucene.analysis.classic.ClassicTokenizer; 12 | 13 | /** 14 | * Analzyer setup for NGrams using the NGramTokenFilter 15 | */ 16 | public class NGramAnalyzer extends Analyzer { 17 | 18 | @SuppressWarnings("resource") 19 | @Override 20 | protected TokenStreamComponents createComponents(String fieldName) { 21 | 22 | Tokenizer tokenizer = new ClassicTokenizer(); 23 | TokenStream stream = new ClassicFilter(tokenizer); 24 | stream = new LowerCaseFilter(stream); 25 | stream = new ClassicFilter(stream); 26 | stream = new NGramTokenFilter(stream, 3, 5, true); 27 | stream = new PorterStemFilter(stream); 28 | stream = new TrimFilter(stream); 29 | 30 | return new TokenStreamComponents(tokenizer, stream); 31 | } 32 | } -------------------------------------------------------------------------------- /lookup/src/main/java/org/dbpedia/lookup/Constants.java: -------------------------------------------------------------------------------- 1 | package org.dbpedia.lookup; 2 | 3 | public class Constants { 4 | 5 | public static final String FIELD_DOCUMENTS = "docs"; 6 | 7 | public static final String FIELD_RESULT = "result"; 8 | 9 | public static final String FIELD_REFCOUNT = "refCount"; 10 | 11 | public static final String FIELD_DOCUMENT_ID = "id"; 12 | 13 | public static final String FIELD_LABEL = "label"; 14 | 15 | public static final String FIELD_DESCRIPTION = "description"; 16 | 17 | public static final String CONFIG_FIELD_FORMAT_XML = "XML"; 18 | 19 | public static final String CONFIG_FIELD_FORMAT_JSON = "JSON"; 20 | 21 | public static final String CONFIG_FIELD_FORMAT_JSON_FULL = "JSON_FULL"; 22 | 23 | public static final String CONFIG_FIELD_FORMAT_JSON_RAW = "JSON_RAW"; 24 | 25 | public static final String CONFIG_FIELD_TYPE_NUMERIC = "numeric"; 26 | 27 | public static final String CONFIG_FIELD_TYPE_STORED = "stored"; 28 | 29 | public static final String CONFIG_FIELD_TYPE_URI = "uri"; 30 | 31 | public static final String CONFIG_FIELD_TYPE_JOIN = "join"; 32 | 33 | public static final String CONFIG_FIELD_TYPE_STORED_SORTED = "stored_sorted"; 34 | 35 | public static final String CONFIG_FIELD_TYPE_STRING = "string"; 36 | 37 | public static final String CONFIG_FIELD_TYPE_TEXT = "text"; 38 | 39 | public static final String CONFIG_FIELD_TYPE_NGRAM = "ngram"; 40 | 41 | } 42 | -------------------------------------------------------------------------------- /lookup/src/main/java/org/dbpedia/lookup/RequestUtils.java: -------------------------------------------------------------------------------- 1 | package org.dbpedia.lookup; 2 | 3 | import java.io.UnsupportedEncodingException; 4 | import java.net.URLDecoder; 5 | 6 | import jakarta.servlet.http.HttpServletRequest; 7 | 8 | public class RequestUtils { 9 | 10 | public static String getStringParameter(HttpServletRequest req, String[] keys, String defaultValue) { 11 | 12 | for (String key : keys) { 13 | 14 | String result = req.getParameter(key); 15 | 16 | if (result != null) { 17 | 18 | try { 19 | return URLDecoder.decode(result, "UTF-8"); 20 | 21 | } catch (UnsupportedEncodingException e) { 22 | return result; 23 | } 24 | } 25 | } 26 | 27 | return defaultValue; 28 | } 29 | 30 | public static float getFloatParameter(HttpServletRequest req, String key, float defaultValue) { 31 | 32 | String result = req.getParameter(key); 33 | 34 | if (result == null) { 35 | return defaultValue; 36 | } 37 | 38 | try { 39 | return Float.parseFloat(result); 40 | } catch (NumberFormatException e) { 41 | return defaultValue; 42 | } 43 | } 44 | 45 | public static int getIntParameter(HttpServletRequest req, String key, int defaultValue) { 46 | 47 | String result = req.getParameter(key); 48 | 49 | if (result == null) { 50 | return defaultValue; 51 | } 52 | 53 | try { 54 | return Integer.parseInt(result); 55 | } catch (NumberFormatException e) { 56 | return defaultValue; 57 | } 58 | } 59 | 60 | public static String getStringParameter(HttpServletRequest req, String key, String defaultValue) { 61 | 62 | String result = req.getParameter(key); 63 | 64 | if (result != null) { 65 | return result; 66 | } 67 | 68 | return defaultValue; 69 | } 70 | 71 | } 72 | -------------------------------------------------------------------------------- /lookup/src/main/resources/logback.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | System.err 4 | 5 | WARN 6 | 7 | 8 | %d{HH:mm:ss} %-5level %msg%n 9 | 10 | 11 | 12 | System.out 13 | 14 | DEBUG 15 | ACCEPT 16 | 17 | 18 | INFO 19 | ACCEPT 20 | 21 | 22 | TRACE 23 | ACCEPT 24 | 25 | 26 | WARN 27 | DENY 28 | 29 | 30 | ERROR 31 | DENY 32 | 33 | 34 | %d{HH:mm:ss} - %msg%n 35 | 36 | 37 | 38 | ./logs/lookup.log 39 | 40 | ./logs/lookup.%d{yyyy-MM-dd}.log 41 | 30 42 | 10GB 43 | 44 | 45 | [%thread] %-5level - %msg%n 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | -------------------------------------------------------------------------------- /lookup/src/main/java/org/dbpedia/lookup/config/LookupField.java: -------------------------------------------------------------------------------- 1 | package org.dbpedia.lookup.config; 2 | 3 | public class LookupField { 4 | 5 | private float weight; 6 | 7 | private String name; 8 | 9 | private String type; 10 | 11 | private String[] aliases; 12 | 13 | private boolean highlight; 14 | 15 | private boolean queryByDefault; 16 | 17 | private boolean isExact; 18 | 19 | private boolean isRequired; 20 | 21 | private boolean tokenize; 22 | 23 | private boolean allowPartialMatch; 24 | 25 | public boolean tokenize() { return tokenize; } 26 | 27 | public void setTokenize(boolean tokenize) { this.tokenize = tokenize; } 28 | 29 | public boolean isHighlight() { 30 | return highlight; 31 | } 32 | 33 | public String getType() { 34 | return type; 35 | } 36 | 37 | public void setType(String type) { 38 | this.type = type; 39 | } 40 | 41 | public boolean isExact() { return isExact; } 42 | 43 | public void setExact(boolean isExact) { this.isExact = isExact; } 44 | 45 | public void setHighlight(boolean highlight) { 46 | this.highlight = highlight; 47 | } 48 | 49 | public float getWeight() { 50 | return weight; 51 | } 52 | 53 | public void setWeight(float weight) { 54 | this.weight = weight; 55 | } 56 | 57 | 58 | 59 | public String getName() { 60 | return name; 61 | } 62 | 63 | public void setName(String fieldName) { 64 | this.name = fieldName; 65 | } 66 | 67 | public boolean isQueryByDefault() { 68 | return queryByDefault; 69 | } 70 | 71 | public void setQueryByDefault(boolean queryByDefault) { 72 | this.queryByDefault = queryByDefault; 73 | } 74 | 75 | public boolean isRequired() { 76 | return isRequired; 77 | } 78 | 79 | public void setRequired(boolean isRequired) { 80 | this.isRequired = isRequired; 81 | } 82 | 83 | /** 84 | * Creates a copy of this query field config object 85 | * @return 86 | */ 87 | public LookupField copy() { 88 | LookupField copy = new LookupField(); 89 | copy.name = this.name; 90 | copy.weight = this.weight; 91 | copy.isRequired = this.isRequired; 92 | copy.queryByDefault = this.queryByDefault; 93 | copy.highlight = this.highlight; 94 | copy.isExact = this.isExact; 95 | copy.tokenize = this.tokenize; 96 | copy.aliases = this.aliases; 97 | copy.allowPartialMatch = this.allowPartialMatch; 98 | copy.type = this.type; 99 | return copy; 100 | } 101 | 102 | public LookupField() { 103 | this.tokenize = true; 104 | } 105 | 106 | public String[] getAliases() { 107 | return aliases; 108 | } 109 | 110 | public void setAliases(String[] aliases) { 111 | this.aliases = aliases; 112 | } 113 | 114 | public boolean isAllowPartialMatch() { 115 | return allowPartialMatch; 116 | } 117 | 118 | public void setAllowPartialMatch(boolean allowPartialMatch) { 119 | this.allowPartialMatch = allowPartialMatch; 120 | } 121 | 122 | } 123 | -------------------------------------------------------------------------------- /lookup/src/main/java/org/dbpedia/lookup/config/QuerySettings.java: -------------------------------------------------------------------------------- 1 | package org.dbpedia.lookup.config; 2 | 3 | import org.dbpedia.lookup.RequestUtils; 4 | 5 | import jakarta.servlet.http.HttpServletRequest; 6 | 7 | /** 8 | * Configuration loaded from a YAML Document. Please refer to the configuration 9 | * documentation 10 | * at https://github.com/dbpedia/lookup-application 11 | * 12 | * @author Jan Forberg 13 | * 14 | */ 15 | public class QuerySettings { 16 | 17 | public static final String EXACT_MATCH_BOOST = "exactMatchBoost"; 18 | 19 | public static final String PREFIX_MATCH_BOOST = "prefixMatchBoost"; 20 | 21 | public static final String MAX_RESULTS = "maxResults"; 22 | 23 | public static final String FORMAT = "format"; 24 | 25 | public static final String MIN_SCORE = "minScore"; 26 | 27 | public static final String FUZZY_MATCH_BOOST = "fuzzyMatchBoost"; 28 | 29 | public static final String FUZZY_PREFIX_LENGTH = "fuzzyPrefixLength"; 30 | 31 | public static final String FUZZY_EDIT_DISTANCE = "fuzzyEditDistance"; 32 | 33 | private float exactMatchBoost; 34 | 35 | private float prefixMatchBoost; 36 | 37 | private int maxResults; 38 | 39 | private int maxResultsCap; 40 | 41 | private String format; 42 | 43 | private float minScore; 44 | 45 | private float fuzzyMatchBoost; 46 | 47 | private int fuzzyPrefixLength = 2; 48 | 49 | private int fuzzyEditDistance = 1; 50 | 51 | public QuerySettings(LookupConfig config) { 52 | exactMatchBoost = config.getExactMatchBoost(); 53 | prefixMatchBoost = config.getPrefixMatchBoost(); 54 | maxResults = config.getMaxResults(); 55 | maxResultsCap = config.getMaxResultsCap(); 56 | format = config.getFormat(); 57 | minScore = config.getMinScore(); 58 | fuzzyEditDistance = config.getFuzzyEditDistance(); 59 | fuzzyMatchBoost = config.getFuzzyMatchBoost(); 60 | fuzzyPrefixLength = config.getFuzzyPrefixLength(); 61 | 62 | if (format == null || format.equals("")) { 63 | format = LookupConfig.CONFIG_FIELD_FORMAT_XML; 64 | } 65 | 66 | } 67 | 68 | public int getFuzzyEditDistance() { 69 | return fuzzyEditDistance; 70 | } 71 | 72 | public int getFuzzyPrefixLength() { 73 | return fuzzyPrefixLength; 74 | } 75 | 76 | public float getFuzzyMatchBoost() { 77 | return fuzzyMatchBoost; 78 | } 79 | 80 | public float getMinScore() { 81 | return minScore; 82 | } 83 | 84 | public float getExactMatchBoost() { 85 | return exactMatchBoost; 86 | } 87 | 88 | public float getPrefixMatchBoost() { 89 | return prefixMatchBoost; 90 | } 91 | 92 | public int getMaxResult() { 93 | return maxResults; 94 | } 95 | 96 | public String getFormat() { 97 | return format; 98 | } 99 | 100 | public void parse(HttpServletRequest req) { 101 | 102 | exactMatchBoost = RequestUtils.getFloatParameter(req, EXACT_MATCH_BOOST, exactMatchBoost); 103 | prefixMatchBoost = RequestUtils.getFloatParameter(req, PREFIX_MATCH_BOOST, prefixMatchBoost); 104 | maxResults = RequestUtils.getIntParameter(req, MAX_RESULTS, maxResults); 105 | 106 | if (maxResultsCap > 0) { 107 | maxResults = Math.min(maxResults, maxResultsCap); 108 | } 109 | 110 | format = RequestUtils.getStringParameter(req, FORMAT, format); 111 | minScore = RequestUtils.getFloatParameter(req, MIN_SCORE, minScore); 112 | fuzzyMatchBoost = RequestUtils.getFloatParameter(req, FUZZY_MATCH_BOOST, fuzzyMatchBoost); 113 | fuzzyEditDistance = RequestUtils.getIntParameter(req, FUZZY_EDIT_DISTANCE, fuzzyEditDistance); 114 | fuzzyPrefixLength = RequestUtils.getIntParameter(req, FUZZY_PREFIX_LENGTH, fuzzyPrefixLength); 115 | } 116 | 117 | 118 | } 119 | -------------------------------------------------------------------------------- /lookup/src/main/java/org/dbpedia/lookup/config/IndexConfig.java: -------------------------------------------------------------------------------- 1 | package org.dbpedia.lookup.config; 2 | 3 | import java.io.File; 4 | import java.io.IOException; 5 | import java.util.List; 6 | 7 | import com.fasterxml.jackson.core.JsonParseException; 8 | import com.fasterxml.jackson.databind.JsonMappingException; 9 | import com.fasterxml.jackson.databind.ObjectMapper; 10 | import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; 11 | 12 | /** 13 | * Configuration loaded from a YAML Document. Please refer to the configuration 14 | * documentation 15 | * at https://github.com/dbpedia/lookup-application 16 | * 17 | * @author Jan Forberg 18 | * 19 | */ 20 | 21 | public class IndexConfig { 22 | 23 | private String version; 24 | 25 | private List indexFields; 26 | 27 | private String indexPath; 28 | 29 | private IndexMode indexMode; 30 | 31 | private String tdbPath; 32 | 33 | private String dataPath; 34 | 35 | private String collectionUri; 36 | 37 | 38 | 39 | private String sparqlEndpoint; 40 | 41 | public String getTdbPath() { 42 | return tdbPath; 43 | } 44 | 45 | public void setTdbPath(String tdbPath) { 46 | this.tdbPath = tdbPath; 47 | } 48 | 49 | public String getDataPath() { 50 | return dataPath; 51 | } 52 | 53 | public void setDataPath(String dataPath) { 54 | this.dataPath = dataPath; 55 | } 56 | 57 | public String getCollectionUri() { 58 | return collectionUri; 59 | } 60 | 61 | public void setCollectionUri(String collectionUri) { 62 | this.collectionUri = collectionUri; 63 | } 64 | 65 | public String getVersion() { 66 | return version; 67 | } 68 | 69 | public void setVersion(String version) { 70 | this.version = version; 71 | } 72 | 73 | public List getIndexFields() { 74 | return indexFields; 75 | } 76 | 77 | public void setIndexFields(List indexFields) { 78 | this.indexFields = indexFields; 79 | } 80 | 81 | public String getIndexPath() { 82 | return indexPath; 83 | } 84 | 85 | public void setIndexPath(String indexPath) { 86 | this.indexPath = indexPath; 87 | } 88 | 89 | public IndexMode getIndexMode() { 90 | return indexMode; 91 | } 92 | 93 | public void setIndexMode(IndexMode indexMode) { 94 | this.indexMode = indexMode; 95 | } 96 | 97 | public String getSparqlEndpoint() { 98 | return sparqlEndpoint; 99 | } 100 | 101 | public void setSparqlEndpoint(String sparqlEndpoint) { 102 | this.sparqlEndpoint = sparqlEndpoint; 103 | } 104 | 105 | /** 106 | * Loads the XML Configuration from file 107 | * 108 | * @param path The path of the file 109 | * @return True if the configuration has been loaded correctly, false otherwise 110 | * @throws IOException 111 | * @throws JsonMappingException 112 | * @throws JsonParseException 113 | * @throws Exception 114 | */ 115 | public static IndexConfig Load(String path) throws JsonParseException, JsonMappingException, IOException { 116 | 117 | ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); 118 | 119 | IndexConfig config = mapper.readValue(new File(path), IndexConfig.class); 120 | 121 | return config; 122 | } 123 | 124 | /** 125 | * Loads the XML Configuration from file 126 | * 127 | * @param path The path of the file 128 | * @return True if the configuration has been loaded correctly, false otherwise 129 | * @throws IOException 130 | * @throws JsonMappingException 131 | * @throws JsonParseException 132 | * @throws Exception 133 | */ 134 | public static IndexConfig FromString(String content) throws JsonParseException, JsonMappingException, IOException { 135 | 136 | ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); 137 | IndexConfig config = mapper.readValue(content, IndexConfig.class); 138 | return config; 139 | } 140 | } 141 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # DBpedia Lookup - Generic RDF Indexer & Searcher 2 | 3 | ## About 4 | 5 | The DBpedia Lookup can be used to index and search the contents of RDF files or databases. 6 | 7 | The search engine is based on the Lucene framework. RDF parsing and SPARQL querying is utilizing the Apache Jena framework, thus supporting a wide range of RDF formats. 8 | 9 | ## How does it work? 10 | 11 | The general idea behind this indexer is leveraging the power of the SPARQL query language to select specific key-value pairs from a knowledge graph and add them to a inverse index. A user can then search over values and quickly retreive associated keys using fuzzy matching. 12 | 13 | In order to create a meaningful index structure, it is important to have a rough understanding of the knowledge graph being indexed and to design the SPARQL queries accordingly. 14 | 15 | A Lucene index can be understood as a collection of documents. Each document has a unique ID and can have multiple fields with one or more values each. The document collection is indexed in a way that documents can be found by searching over the values of all or only some fields. The lookup indexer handles the process of converting a knowledge graph into such a document collection. 16 | 17 | ## Quickstart Example 18 | 19 | The [examples folder](https://github.com/dbpedia/dbpedia-lookup/tree/main/examples) contains configuration files for a search index over a part of the **DBpedia knowledge graph** (using [https://dbpedia.org/sparql](https://dbpedia.org/sparql)). 20 | 21 | It contains 22 | 23 | * a configuration file for the lookup server instance ([config.yml](https://github.com/dbpedia/dbpedia-lookup/tree/main/examples/config.yml)) 24 | * a configuration file for the indexing request ([dbpedia-resource-indexer.yml](https://github.com/dbpedia/dbpedia-lookup/tree/main/examples/indexing/dbpedia-resource-indexer.yml)) 25 | 26 | ### Step 1 27 | Run a server instance using the provided configuration in [config.yml](https://github.com/dbpedia/dbpedia-lookup/tree/main/examples/config.yml). 28 | 29 | You can run the *"Launch Lookup Server"* setup from the [launch-config.json](../.vscode/launch.json) in Visual Studio Code. 30 | Alternatively, you can use maven to build a `.jar` file by issuing 31 | 32 | ``` 33 | mvn package 34 | ``` 35 | and then running the resulting `lookup-1.0-jar-with-dependencies.jar` file via 36 | ``` 37 | java -jar ./target/lookup-1.0-jar-with-dependencies.jar -c ../examples/config.yml 38 | ``` 39 | 40 | ### Step 2 41 | 42 | Run the indexing process. Issue the following HTTP request: 43 | 44 | ``` 45 | curl --request POST \ 46 | --url http://localhost:8082/api/index/run \ 47 | --header 'Content-Type: multipart/form-data' \ 48 | --form config=@index-config.yml \ 49 | --form values=http://dbpedia.org/resource/Berlin,http://dbpedia.org/resource/Leipzig,http://dbpedia.org/resource/Hamburg 50 | ``` 51 | 52 | This will send and indexing request to the indexer API that will fetch indexable data for the specified resource URIs from the DBpedia knowledge graph 53 | 54 | ### Step 3 55 | 56 | Subsequently, the following request should return a result with the DBpedia entry of the city Berlin. 57 | 58 | ``` 59 | curl http://localhost:8082/api/search?query=Ber 60 | ``` 61 | 62 | ## Configurations 63 | 64 | There are two types of configuration files for lookup, each with their own documentation: 65 | 66 | * **Indexing Configuration:** [here](./doc/indexing.md). 67 | * **Server Configuration:** [here](./doc/server.md) 68 | 69 | ## Discussion 70 | 71 | There is a discussion thread on the DBpedia forums for questions and suggestions concerning this app and service [here](https://forum.dbpedia.org/t/new-dbpedia-lookup-application/607). 72 | 73 | ## Building the Docker Image 74 | 75 | In order to build the docker image run: 76 | ``` 77 | cd lookup 78 | mvn package 79 | docker build -t lookup . 80 | ``` 81 | 82 | Do this before running `docker compose up`. 83 | -------------------------------------------------------------------------------- /lookup/src/main/java/org/dbpedia/lookup/server/LookupIndexerServlet.java: -------------------------------------------------------------------------------- 1 | package org.dbpedia.lookup.server; 2 | 3 | import java.io.IOException; 4 | import java.nio.file.Files; 5 | import java.nio.file.Path; 6 | import java.util.Collection; 7 | import jakarta.servlet.MultipartConfigElement; 8 | import jakarta.servlet.ServletException; 9 | import jakarta.servlet.http.HttpServlet; 10 | import jakarta.servlet.http.HttpServletRequest; 11 | import jakarta.servlet.http.HttpServletResponse; 12 | import jakarta.servlet.http.Part; 13 | 14 | import org.apache.lucene.index.IndexWriter; 15 | import org.dbpedia.lookup.config.IndexConfig; 16 | import org.dbpedia.lookup.indexer.LookupIndexer; 17 | import org.dbpedia.lookup.searcher.LookupSearcher; 18 | import org.eclipse.jetty.server.Request; 19 | import org.slf4j.Logger; 20 | import org.slf4j.LoggerFactory; 21 | 22 | /** 23 | * HTTP Servlet with handlers for the single lookup API request "/api/search" 24 | * Post-processes requests and sends the query to the LuceneLookupSearcher, 25 | * which translates requests into lucene queries 26 | */ 27 | public class LookupIndexerServlet extends HttpServlet { 28 | 29 | final static Logger logger = LoggerFactory.getLogger(LookupIndexerServlet.class); 30 | 31 | final static String PATH_RUN = "/run"; 32 | 33 | final static String PATH_DELETE = "/delete"; 34 | 35 | final static String PATH_CLEAR = "/clear"; 36 | 37 | final static String FORM_FIELD_VALUES = "values"; 38 | 39 | final static String FORM_FIELD_CONFIG = "config"; 40 | 41 | private IndexWriter indexWriter; 42 | 43 | private LookupIndexer indexer; 44 | 45 | private LookupSearcher searcher; 46 | 47 | @Override 48 | public void init() throws ServletException { 49 | indexer = (LookupIndexer)getServletContext().getAttribute("INDEXER"); 50 | searcher = (LookupSearcher)getServletContext().getAttribute("SEARCHER"); 51 | } 52 | 53 | @Override 54 | public void destroy() { 55 | try { 56 | indexWriter.close(); 57 | } catch (IOException e) { 58 | e.printStackTrace(); 59 | } 60 | super.destroy(); 61 | } 62 | 63 | @Override 64 | protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { 65 | 66 | String pathInfo = req.getPathInfo(); 67 | 68 | if(PATH_RUN.equals(pathInfo)) { 69 | doRun(req, res); 70 | } 71 | 72 | if(PATH_DELETE.equals(pathInfo)) { 73 | doDrop(req, res); 74 | } 75 | 76 | if(PATH_CLEAR.equals(pathInfo)) { 77 | doClear(req, res); 78 | } 79 | } 80 | 81 | private void doDrop(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { 82 | // Set up the temporary directory for storing uploaded files 83 | Path tempDirectory = Files.createTempDirectory("multipart"); 84 | MultipartConfigElement multipartConfigElement = new MultipartConfigElement(tempDirectory.toString()); 85 | 86 | // Set the multipart configuration for the request 87 | req.setAttribute(Request.__MULTIPART_CONFIG_ELEMENT, multipartConfigElement); 88 | 89 | // Get the files from the multipart form 90 | Collection parts = req.getParts(); 91 | 92 | String[] values = null; 93 | 94 | // Process files 95 | for (Part part : parts) { 96 | String partName = part.getName(); 97 | byte[] partBytes = part.getInputStream().readAllBytes(); 98 | String partValue = new String(partBytes, java.nio.charset.StandardCharsets.UTF_8); 99 | 100 | if(FORM_FIELD_VALUES.equals(partName)) { 101 | values = partValue.split(","); 102 | } 103 | } 104 | 105 | 106 | indexer.drop(values); 107 | searcher.refresh(); 108 | res.setStatus(HttpServletResponse.SC_OK); 109 | } 110 | 111 | private void doClear(HttpServletRequest req, HttpServletResponse res) { 112 | indexer.clear(); 113 | searcher.refresh(); 114 | res.setStatus(HttpServletResponse.SC_OK); 115 | } 116 | 117 | private void doRun(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { 118 | // Set up the temporary directory for storing uploaded files 119 | Path tempDirectory = Files.createTempDirectory("multipart"); 120 | MultipartConfigElement multipartConfigElement = new MultipartConfigElement(tempDirectory.toString()); 121 | 122 | // Set the multipart configuration for the request 123 | req.setAttribute(Request.__MULTIPART_CONFIG_ELEMENT, multipartConfigElement); 124 | 125 | // Get the files from the multipart form 126 | Collection parts = req.getParts(); 127 | 128 | IndexConfig indexConfig = null; 129 | String[] values = null; 130 | 131 | // Process files 132 | for (Part part : parts) { 133 | String partName = part.getName(); 134 | byte[] partBytes = part.getInputStream().readAllBytes(); 135 | String partValue = new String(partBytes, java.nio.charset.StandardCharsets.UTF_8); 136 | 137 | System.out.println("Form Field: " + part.getName()); 138 | System.out.println("Form Value: " + partValue); 139 | 140 | if(FORM_FIELD_CONFIG.equals(partName)) { 141 | indexConfig = IndexConfig.FromString(partValue); 142 | } 143 | 144 | if(FORM_FIELD_VALUES.equals(partName)) { 145 | values = partValue.split(","); 146 | } 147 | } 148 | 149 | indexer.run(indexConfig, values); 150 | searcher.refresh(); 151 | 152 | // Respond to the request 153 | res.setStatus(HttpServletResponse.SC_OK); 154 | return; 155 | } 156 | 157 | 158 | 159 | 160 | 161 | 162 | } 163 | -------------------------------------------------------------------------------- /lookup/src/main/java/org/dbpedia/lookup/config/LookupConfig.java: -------------------------------------------------------------------------------- 1 | package org.dbpedia.lookup.config; 2 | 3 | import java.io.File; 4 | 5 | import com.fasterxml.jackson.databind.ObjectMapper; 6 | import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; 7 | 8 | /** 9 | * Configuration loaded from a YAML Document. Please refer to the configuration documentation 10 | * at https://github.com/dbpedia/lookup-application 11 | * @author Jan Forberg 12 | * 13 | */ 14 | public class LookupConfig { 15 | 16 | public static final String CONFIG_FIELD_FORMAT_XML = "XML"; 17 | 18 | public static final String CONFIG_FIELD_FORMAT_JSON = "JSON"; 19 | 20 | public static final String CONFIG_FIELD_FORMAT_JSON_FULL = "JSON_FULL"; 21 | 22 | public static final String CONFIG_FIELD_FORMAT_JSON_RAW = "JSON_RAW"; 23 | 24 | public static final String CONFIG_FIELD_TYPE_NUMERIC = "numeric"; 25 | 26 | public static final String CONFIG_FIELD_TYPE_STORED = "stored"; 27 | 28 | public static final String CONFIG_FIELD_TYPE_STRING = "string"; 29 | 30 | public static final String CONFIG_FIELD_TYPE_TEXT = "text"; 31 | 32 | private String version; 33 | 34 | private String indexPath; 35 | 36 | private float exactMatchBoost; 37 | 38 | private LookupField[] lookupFields; 39 | 40 | private float prefixMatchBoost; 41 | 42 | private float fuzzyMatchBoost; 43 | 44 | private int fuzzyEditDistance; 45 | 46 | private int fuzzyPrefixLength; 47 | 48 | private int maxResults; 49 | 50 | private int logInterval; 51 | 52 | public int getLogInterval() { 53 | return logInterval; 54 | } 55 | 56 | public void setLogInterval(int logInterval) { 57 | this.logInterval = logInterval; 58 | } 59 | 60 | private int maxBufferedDocs; 61 | 62 | public int getMaxBufferedDocs() { 63 | return maxBufferedDocs; 64 | } 65 | 66 | public void setMaxBufferedDocs(int maxBufferedDocs) { 67 | this.maxBufferedDocs = maxBufferedDocs; 68 | } 69 | 70 | private int maxResultsCap; 71 | 72 | private float minScore; 73 | 74 | private String boostFormula; 75 | 76 | private String format; 77 | 78 | private String formatTemplate; 79 | 80 | public String getIndexPath() { 81 | return indexPath; 82 | } 83 | 84 | public void setIndexPath(String indexPath) { 85 | this.indexPath = indexPath; 86 | } 87 | 88 | public float getExactMatchBoost() { 89 | return exactMatchBoost; 90 | } 91 | 92 | public void setExactMatchBoost(float exactMatchBoost) { 93 | this.exactMatchBoost = exactMatchBoost; 94 | } 95 | 96 | public LookupField[] getLookupFields() { 97 | return lookupFields; 98 | } 99 | 100 | public void setLookupFields(LookupField[] queryFields) { 101 | this.lookupFields = queryFields; 102 | } 103 | 104 | public float getPrefixMatchBoost() { 105 | return prefixMatchBoost; 106 | } 107 | 108 | public void setPrefixMatchBoost(float prefixMatchBoost) { 109 | this.prefixMatchBoost = prefixMatchBoost; 110 | } 111 | 112 | public float getFuzzyMatchBoost() { 113 | return fuzzyMatchBoost; 114 | } 115 | 116 | public void setFuzzyMatchBoost(float fuzzyMatchBoost) { 117 | this.fuzzyMatchBoost = fuzzyMatchBoost; 118 | } 119 | 120 | public int getFuzzyEditDistance() { 121 | return fuzzyEditDistance; 122 | } 123 | 124 | public void setFuzzyEditDistance(int fuzzyEditDistance) { 125 | this.fuzzyEditDistance = fuzzyEditDistance; 126 | } 127 | 128 | public int getFuzzyPrefixLength() { 129 | return fuzzyPrefixLength; 130 | } 131 | 132 | public void setFuzzyPrefixLength(int fuzzyPrefixLength) { 133 | this.fuzzyPrefixLength = fuzzyPrefixLength; 134 | } 135 | 136 | public int getMaxResults() { 137 | return maxResults; 138 | } 139 | 140 | public void setMaxResults(int maxResults) { 141 | this.maxResults = maxResults; 142 | } 143 | 144 | public String getBoostFormula() { 145 | return boostFormula; 146 | } 147 | 148 | public void setBoostFormula(String boostFormula) { 149 | this.boostFormula = boostFormula; 150 | } 151 | 152 | public float getMinScore() { 153 | return minScore; 154 | } 155 | 156 | public void setMinScore(float minScore) { 157 | this.minScore = minScore; 158 | } 159 | 160 | public String getFormat() { 161 | return format; 162 | } 163 | 164 | public void setFormat(String format) { 165 | this.format = format; 166 | } 167 | 168 | public String getFormatTemplate() { 169 | return formatTemplate; 170 | } 171 | 172 | public void setFormatTemplate(String formatTemplate) { 173 | this.formatTemplate = formatTemplate; 174 | } 175 | 176 | public int getMaxResultsCap() { 177 | return maxResultsCap; 178 | } 179 | 180 | public void setMaxResultsCap(int maxResultsCap) { 181 | this.maxResultsCap = maxResultsCap; 182 | } 183 | 184 | public String getVersion() { 185 | return version; 186 | } 187 | 188 | public void setVersion(String version) { 189 | this.version = version; 190 | } 191 | 192 | 193 | 194 | /** 195 | * Loads the XML Configuration from file 196 | * @param path The path of the file 197 | * @return True if the configuration has been loaded correctly, false otherwise 198 | * @throws Exception 199 | */ 200 | public static LookupConfig Load(String path) throws Exception { 201 | 202 | ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); 203 | 204 | LookupConfig config = mapper.readValue(new File(path), LookupConfig.class); 205 | 206 | return config; 207 | } 208 | 209 | public LookupConfig copy() { 210 | return null; 211 | } 212 | 213 | public LookupField getLookupField(String fieldName) { 214 | for(LookupField field : lookupFields) { 215 | if(field.getName() == null) { 216 | continue; 217 | } 218 | 219 | if(field.getName().equals(fieldName)) { 220 | return field; 221 | } 222 | } 223 | 224 | return null; 225 | } 226 | } 227 | 228 | -------------------------------------------------------------------------------- /lookup/src/main/java/org/dbpedia/lookup/DatabusUtils.java: -------------------------------------------------------------------------------- 1 | package org.dbpedia.lookup; 2 | 3 | import java.io.File; 4 | import java.io.FileOutputStream; 5 | import java.io.IOException; 6 | import java.net.URI; 7 | import java.net.URISyntaxException; 8 | import java.net.URL; 9 | import java.net.URLEncoder; 10 | import java.nio.file.Files; 11 | import java.nio.file.Path; 12 | import java.nio.file.Paths; 13 | import java.util.ArrayList; 14 | import java.util.regex.Matcher; 15 | import java.util.regex.Pattern; 16 | 17 | import org.apache.commons.codec.digest.DigestUtils; 18 | import org.apache.http.HttpEntity; 19 | import org.apache.http.HttpResponse; 20 | import org.apache.http.ParseException; 21 | import org.apache.http.client.HttpClient; 22 | import org.apache.http.client.methods.HttpGet; 23 | import org.apache.http.client.methods.HttpPost; 24 | import org.apache.http.entity.ByteArrayEntity; 25 | import org.apache.http.impl.client.HttpClientBuilder; 26 | import org.apache.http.impl.client.LaxRedirectStrategy; 27 | import org.apache.http.util.EntityUtils; 28 | import org.json.JSONArray; 29 | import org.json.JSONObject; 30 | import org.slf4j.Logger; 31 | 32 | public class DatabusUtils { 33 | 34 | public static File[] loadDatabusFiles(String collectionUri, Logger logger) { 35 | ArrayList result = new ArrayList(); 36 | 37 | try { 38 | String query = get("GET", collectionUri, "text/sparql"); 39 | logger.info("Collections resolved to query"); 40 | logger.info(query); 41 | 42 | // depending on running system, daytime or weather condition, the query is either already URL encoded or still plain text 43 | if(!isURLEncoded(query)) { 44 | query = URLEncoder.encode(query, "UTF-8"); 45 | } 46 | 47 | URL url = new URI(collectionUri).toURL(); 48 | String baseUrl = getBaseUrl(url); 49 | String queryResult = query(baseUrl + "/sparql", query); 50 | ArrayList fileUris = new ArrayList(); 51 | JSONObject obj = new JSONObject(queryResult); 52 | JSONArray bindings = obj.getJSONObject("results").getJSONArray("bindings"); 53 | 54 | for (int i = 0; i < bindings.length(); i++) 55 | { 56 | JSONObject binding = bindings.getJSONObject(i); 57 | String key = binding.keys().next(); 58 | JSONObject jsonObject = binding.getJSONObject(key); 59 | fileUris.add(jsonObject.getString("value")); 60 | } 61 | 62 | 63 | String collectionUriHash = DigestUtils.md5Hex(collectionUri); 64 | File tmpdir = Files.createTempDirectory(collectionUriHash).toFile(); 65 | 66 | for(String fileUri : fileUris) { 67 | 68 | logger.info("Downloading file: " + fileUri); 69 | String filename = fileUri.substring(fileUri.lastIndexOf('/') + 1); 70 | 71 | String prefix = filename; 72 | String suffixes = ""; 73 | 74 | if(filename.contains(".")) { 75 | prefix = filename.substring(0,filename.indexOf('.')); 76 | suffixes = filename.substring(filename.indexOf('.')); 77 | } 78 | 79 | String hash = DigestUtils.md5Hex(fileUri).toUpperCase().substring(0,4); 80 | String uniqname = prefix + "_" + hash + suffixes; 81 | 82 | HttpClient instance = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build(); 83 | HttpResponse response = instance.execute(new HttpGet(fileUri)); 84 | 85 | Path path = Paths.get(tmpdir.getAbsolutePath() + "/" + uniqname); 86 | File file = path.toFile(); 87 | response.getEntity().writeTo(new FileOutputStream(file,false)); 88 | 89 | result.add(file); 90 | logger.info("File saved to " + path.toAbsolutePath().toString()); 91 | } 92 | } catch (IOException e) { 93 | e.printStackTrace(); 94 | } catch (URISyntaxException e) { 95 | e.printStackTrace(); 96 | } 97 | 98 | return result.toArray(new File[0]); 99 | } 100 | 101 | private static String query(String endpoint, String query) throws ParseException, IOException { 102 | 103 | HttpClient client = HttpClientBuilder.create().build(); 104 | String body = "default-graph-uri=&format=application%2Fsparql-results%2Bjson&query=" + query; 105 | HttpEntity entity = new ByteArrayEntity(body.getBytes("UTF-8")); 106 | HttpPost request = new HttpPost(endpoint); 107 | request.setEntity(entity); 108 | request.setHeader("Content-type", "application/x-www-form-urlencoded"); 109 | HttpResponse response = client.execute(request); 110 | HttpEntity responseEntity = response.getEntity(); 111 | 112 | if(responseEntity != null) { 113 | return EntityUtils.toString(responseEntity); 114 | } 115 | 116 | return null; 117 | } 118 | 119 | private static boolean isURLEncoded(String query) { 120 | 121 | Pattern hasWhites = Pattern.compile("\\s+"); 122 | Matcher matcher = hasWhites.matcher(query); 123 | return !matcher.find(); 124 | } 125 | 126 | public static String getBaseUrl(URL url) { 127 | StringBuilder baseUrl = new StringBuilder(); 128 | baseUrl.append(url.getProtocol()).append("://").append(url.getHost()); 129 | 130 | int port = url.getPort(); 131 | if (port != -1) { 132 | baseUrl.append(":").append(port); 133 | } 134 | 135 | return baseUrl.toString(); 136 | } 137 | 138 | private static String get(String method, String urlString, String accept) throws IOException { 139 | 140 | System.out.println(method + ": " + urlString + " / ACCEPT: " + accept); 141 | 142 | HttpClient client = HttpClientBuilder.create().build(); 143 | 144 | if(method.equals("GET")) { 145 | 146 | HttpGet request = new HttpGet(urlString); 147 | request.addHeader("Accept", accept); 148 | HttpResponse response = client.execute(request); 149 | HttpEntity responseEntity = response.getEntity(); 150 | 151 | if(responseEntity != null) { 152 | return EntityUtils.toString(responseEntity); 153 | } 154 | } 155 | 156 | return null; 157 | } 158 | } 159 | -------------------------------------------------------------------------------- /lookup/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | dbpedia.org 7 | lookup 8 | 1.0 9 | lookup 10 | https://github.com/dbpedia/dbpedia-lookup 11 | 12 | UTF-8 13 | 1.8 14 | 1.8 15 | 16 | 17 | 18 | org.apache.zookeeper 19 | zookeeper 20 | 3.8.0 21 | 22 | 23 | junit 24 | junit 25 | 4.11 26 | test 27 | 28 | 29 | org.apache.lucene 30 | lucene-core 31 | 9.10.0 32 | 33 | 34 | org.apache.lucene 35 | lucene-join 36 | 9.10.0 37 | 38 | 39 | org.apache.lucene 40 | lucene-queryparser 41 | 9.10.0 42 | 43 | 44 | org.apache.lucene 45 | lucene-analysis-common 46 | 9.10.0 47 | 48 | 49 | org.apache.lucene 50 | lucene-expressions 51 | 9.10.0 52 | 53 | 54 | org.apache.lucene 55 | lucene-highlighter 56 | 9.10.0 57 | 58 | 59 | org.apache.jena 60 | apache-jena-libs 61 | pom 62 | 3.14.0 63 | 64 | 65 | org.json 66 | json 67 | 20180813 68 | 69 | 70 | com.fasterxml.jackson.dataformat 71 | jackson-dataformat-yaml 72 | 2.3.0 73 | 74 | 75 | org.apache.logging.log4j 76 | log4j-web 77 | 2.16.0 78 | 79 | 80 | javax.servlet 81 | javax.servlet-api 82 | 4.0.1 83 | provided 84 | 85 | 86 | org.apache.commons 87 | commons-compress 88 | 1.19 89 | 90 | 91 | org.glassfish.jersey.containers 92 | jersey-container-jdk-http 93 | 2.25 94 | 95 | 96 | com.sun.net.httpserver 97 | http 98 | 20070405 99 | test 100 | 101 | 102 | commons-cli 103 | commons-cli 104 | 1.3.1 105 | 106 | 107 | net.sf.saxon 108 | Saxon-HE 109 | 10.1 110 | 111 | 112 | com.fasterxml.jackson.core 113 | jackson-databind 114 | 2.3.0 115 | 116 | 117 | org.eclipse.jetty 118 | jetty-server 119 | 11.0.3 120 | 121 | 122 | 123 | org.eclipse.jetty 124 | jetty-util 125 | 11.0.3 126 | 127 | 128 | org.eclipse.jetty 129 | jetty-servlet 130 | 11.0.3 131 | 132 | 133 | org.eclipse.jetty 134 | jetty-servlets 135 | 11.0.3 136 | 137 | 138 | org.slf4j 139 | slf4j-api 140 | 2.0.2 141 | 142 | 143 | ch.qos.logback 144 | logback-classic 145 | 1.4.5 146 | 147 | 148 | ch.qos.logback 149 | logback-core 150 | 1.4.5 151 | 152 | 153 | 154 | 155 | 156 | 157 | org.apache.maven.plugins 158 | maven-assembly-plugin 159 | 160 | 161 | make-assembly 162 | package 163 | 164 | single 165 | 166 | 167 | 168 | 169 | 170 | 171 | org.dbpedia.lookup.Main 172 | 173 | 174 | 175 | jar-with-dependencies 176 | 177 | 178 | 179 | 180 | 181 | -------------------------------------------------------------------------------- /examples/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | DBpedia Lookup 6 | 7 | 8 | 96 | 97 | 98 |
99 |
100 | 101 |

Lookup

102 |
103 | 106 |
107 |

Search:

108 |
109 | 110 | 111 |
112 |
113 |

Top 10 Results:

114 |
115 |
No results
116 |
117 |
118 |
119 |
120 | 173 | 174 | 175 | 176 | -------------------------------------------------------------------------------- /doc/indexing.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | ### Example Configuration 4 | 5 | A simple example [index configuration](../examples/indexing/dbpedia-resource-indexer.yml) looks as follows: 6 | ```yaml 7 | version: "1.0" 8 | indexMode: INDEX_SPARQL_ENDPOINT 9 | sparqlEndpoint: https://dbpedia.org/sparql 10 | indexFields: 11 | - fieldName: label 12 | documentVariable: resource 13 | query: > 14 | SELECT ?resource ?label WHERE { 15 | { 16 | ?resource ?label . 17 | FILTER(lang(?label) = 'en') 18 | #VALUES# 19 | } 20 | } 21 | LIMIT 10000 22 | ``` 23 | 24 | The configuration fields describe the following (some less important fields are not described here and can be found in the configurations sections below): 25 | 26 | * **indexMode:** In this example, we are indexing a knowledge graph using its SPARQL endpoint, hence index mode is set to INDEX_SPARQL_ENDPOINT. 27 | * **sparqlEndpoint:** Needs to be specified when *indexMode* is set to INDEX_SPARQL_ENDPOINT. In this example, this points to the SPARQL endpoint of the DBpedia knowledge graph 28 | * **indexFields:** The index fields are the core of a lookup indexer configuration. The conist of a list of index field objects that consist of the following: 29 | * **fieldName:** The name of the field to be indexed. This is **also** the name of the variable in the query that will hold the field values 30 | * **documentVariable:** The name of the variable in the query that will hold the ID of the target lucene document. 31 | * **query:** The query describing the selection of document ID and field value from the target knowledge graph. 32 | * the **#VALUES#** comment in the query: #VALUES# is a SPARQL comment and thus usually ignored. It acts as a placeholder for a SPARQL VALUES clause that gets inserted automatically when passing a list of URIs to the indexing process via the `values` parameter. This can be used to only retrieve bindings for a specific set of resources. 33 | 34 | ### Testing the Queries 35 | 36 | Before running the indexer, it is best to test each query in order to rule out any bugs that might be hard to trace later on. 37 | 38 | Since this current example is configured to run queries against a SPARQL endpoint (index mode set to INDEX_SPARQL_ENDPOINT with [https://dbpedia.org/sparql](https://dbpedia.org/sparql)) we can simply test our queries via HTTP requests. The first configured query could be tested, by running 39 | 40 | ```sparql 41 | SELECT ?resource ?label WHERE { 42 | { 43 | ?resource ?label . 44 | FILTER(lang(?label) = 'en') 45 | #VALUES# 46 | } 47 | } 48 | LIMIT 10000 49 | ``` 50 | 51 | against the [DBpedia SPARQL endpoint](https://dbpedia.org/sparql?default-graph-uri=http%3A%2F%2Fdbpedia.org&query=SELECT+%3Fcity+%3Flabel+WHERE+%7B%0D%0A++++++++%7B%0D%0A++++++++++%3Fcity+a+%3Chttp%3A%2F%2Fdbpedia.org%2Fontology%2FCity%3E+.%0D%0A++++++++++%3Fcity+%3Chttp%3A%2F%2Fwww.w3.org%2F2000%2F01%2Frdf-schema%23label%3E+%3Flabel+.%0D%0A++++++++++FILTER+%28LANG%28%3Flabel%29+%3D+%22en%22%29.%0D%0A++++++++%7D%0D%0A++++++%7D+LIMIT+10000&format=text%2Fhtml&timeout=30000&signal_void=on&signal_unconnected=on). 52 | 53 | The result is a list of bindings with two entries. The first entry (*city*) will be used a document ID, while the second value (*label*) will be written to each respective document under the field *label*. A document created by this query could look like the following: 54 | 55 | ``` 56 | Document 57 | id: 'http://dbpedia.org/resource/Berlin' 58 | label: 'Berlin' 59 | ``` 60 | 61 | A user searching for the string "Berl" over the field *label* will then be able to quickly retrieve the entire document, since the label field value partially matches the search string. 62 | 63 | ## Configuration 64 | 65 | ### indexPath 66 | The path of the target folder for the index structure (*absolute* or *relative to the configuration file*). This can be either an empty folder or a folder containing an already existing index structure. 67 | 68 | ### dataPath 69 | *[Optional]* This variable is only required when indexing the contents of RDF files. Points to the folder containing the files to index. 70 | 71 | ### databasePath 72 | *[Optional]* This variable is only required when running with either build mode [BUILD_AND_INDEX_ON_DISK](#build_and_index_on_disk) or [INDEX_ON_DISK](#index_on_disk). Specifies the path of the on-disk graph database which is required for both modes. 73 | 74 | ### sparqlEndpoint 75 | *[Optional]* Only needs to be specified when [indexMode](#indexmode) is set to [INDEX_SPARQL_ENDPOINT](#index_sparql_endpoint). Specifies the target SPARQL endpoint URL. 76 | 77 | ### indexMode 78 | Defines the indexing approach. Has to be one of [INDEX_IN_MEMORY](#index_in_memory), [BUILD_AND_INDEX_ON_DISK](#build_and_index_on_disk), [INDEX_ON_DISK](#index_on_disk) or [INDEX_SPARQL_ENDPOINT](#index_sparql_endpoint) (see enum [IndexMode](../lookup-indexer/src/main/java/org/dbpedia/lookup/config/IndexMode.java)). The index modes change the behaviour of the lookup indexer as follows: 79 | 80 | #### INDEX_IN_MEMORY 81 | The indexer loads the content of the RDF files defined at [dataPath](#datapath) into an in-memory graph database, which is then used to execute the configured SPARQL queries. Only works for small to medium files, since the index structure can eat up a lot of RAM. 82 | 83 | #### BUILD_AND_INDEX_ON_DISK 84 | Similar to [INDEX_IN_MEMORY](#index_in_memory), but the graph database is created on-disk (see [TDB2](https://jena.apache.org/documentation/tdb2/)). This takes considerably more time and makes querying slower but can handle much larger files, since disk space is generally more abundant than memory. The on-disk graph database will be created at the path specified in *databasePath** 85 | 86 | #### INDEX_ON_DISK 87 | Same as [BUILD_AND_INDEX_ON_DISK](#build_and_index_on_disk) but skips the on-disk graph database creation step. This mode tries to load an existing on-disk graph database from [databasePath](#databasepath) as a SPARQL query target. 88 | 89 | #### INDEX_SPARQL_ENDPOINT 90 | Runs the configured queries against the SPARQL endpoint URL specified in [sparqlEndpoint](#sparqlendpoint). 91 | 92 | ### indexFields 93 | The index fields are the core of a lookup indexer configuration. The consist of a list of index field objects that have the following subfields: 94 | 95 | #### fieldName 96 | The name of the field to be indexed. This is **also** the name of the variable in the query that will hold the field values 97 | #### documentVariable 98 | The name of the variable in the query that will hold the ID of the target lucene document. Has to match one of the binding variables selected in [query](#query). 99 | #### query 100 | The SPARQL select query describing the selection of document ID and field value from the target knowledge graph. The binding variables of the select query must contain variable names matching the values specified in [fieldName](#fieldname) and [documentVariable](#documentvariable). 101 | -------------------------------------------------------------------------------- /lookup/src/main/java/org/dbpedia/lookup/server/LookupSearcherServlet.java: -------------------------------------------------------------------------------- 1 | package org.dbpedia.lookup.server; 2 | 3 | import java.io.FileInputStream; 4 | import java.io.FileNotFoundException; 5 | import java.io.IOException; 6 | import java.io.PrintWriter; 7 | import java.io.StringWriter; 8 | import java.io.UnsupportedEncodingException; 9 | import java.net.URLDecoder; 10 | import java.util.Hashtable; 11 | 12 | import jakarta.servlet.ServletException; 13 | import jakarta.servlet.http.HttpServlet; 14 | import jakarta.servlet.http.HttpServletRequest; 15 | import jakarta.servlet.http.HttpServletResponse; 16 | 17 | import javax.xml.transform.Result; 18 | import javax.xml.transform.Source; 19 | import javax.xml.transform.Templates; 20 | import javax.xml.transform.Transformer; 21 | import javax.xml.transform.TransformerConfigurationException; 22 | import javax.xml.transform.TransformerException; 23 | import javax.xml.transform.TransformerFactory; 24 | import javax.xml.transform.stream.StreamResult; 25 | import javax.xml.transform.stream.StreamSource; 26 | 27 | import org.apache.zookeeper.common.Time; 28 | import org.dbpedia.lookup.Main; 29 | import org.dbpedia.lookup.RequestUtils; 30 | import org.dbpedia.lookup.config.LookupConfig; 31 | import org.dbpedia.lookup.config.LookupField; 32 | import org.dbpedia.lookup.config.QuerySettings; 33 | import org.dbpedia.lookup.searcher.LookupSearcher; 34 | import org.json.JSONObject; 35 | import org.json.XML; 36 | import org.slf4j.Logger; 37 | import org.slf4j.LoggerFactory; 38 | 39 | /** 40 | * HTTP Servlet with handlers for the single lookup API request "/api/search" 41 | * Post-processes requests and sends the query to the LuceneLookupSearcher, 42 | * which translates requests into lucene queries 43 | */ 44 | public class LookupSearcherServlet extends HttpServlet { 45 | 46 | /** 47 | * 48 | */ 49 | private static final long serialVersionUID = 102831973239L; 50 | 51 | private static final String VERSION_TAG = "v0.001"; 52 | 53 | public static final String PATH_REFRESH = "/refresh"; 54 | 55 | public static final String QUERY_SUFFIX_WEIGHT = "Weight"; 56 | 57 | public static final String QUERY_SUFFIX_REQUIRED = "Required"; 58 | 59 | public static final String QUERY_SUFFIX_EXACT = "Exact"; 60 | 61 | public static final String QUERY_SUFFIX_TOKENIZE = "Tokenize"; 62 | 63 | public static final String QUERY_SUFFIX_HIGHLIGHT = "Highlight"; 64 | 65 | public static final String QUERY_SUFFIX_ALLOW_PARTIAL_MATCH = "AllowPartialMatch"; 66 | 67 | private LookupSearcher searcher; 68 | 69 | private LookupConfig queryConfig; 70 | 71 | private Transformer xformer; 72 | 73 | public static final String CONFIG_PATH = "configpath"; 74 | 75 | private static final String[] PARAM_QUERY = { "QueryString", "query" }; 76 | 77 | private static final String PARAM_JOIN = "join"; 78 | 79 | private String initializationError; 80 | 81 | final static Logger logger = LoggerFactory.getLogger(LookupSearcherServlet.class); 82 | 83 | @Override 84 | public void init() throws ServletException { 85 | 86 | System.out.println("Initializing Lookup Searcher " + VERSION_TAG); 87 | searcher = (LookupSearcher)getServletContext().getAttribute("SEARCHER"); 88 | 89 | String configPath = getInitParameter(Main.CONFIG_PATH); 90 | try { 91 | queryConfig = LookupConfig.Load(configPath); 92 | 93 | for(LookupField field : queryConfig.getLookupFields()) { 94 | System.out.println(field.getName() + " -- " + field.getType() + " -- " + field.getWeight()); 95 | } 96 | } catch (Exception e) { 97 | e.printStackTrace(); 98 | } 99 | 100 | TransformerFactory transformerFactory = new net.sf.saxon.TransformerFactoryImpl(); 101 | 102 | if (queryConfig.getFormatTemplate() != null) { 103 | 104 | try { 105 | Templates formatTemplate = transformerFactory.newTemplates(new StreamSource( 106 | new FileInputStream(queryConfig.getFormatTemplate()))); 107 | 108 | xformer = formatTemplate.newTransformer(); 109 | } catch (TransformerConfigurationException | FileNotFoundException e1) { 110 | // this is logged to catalina.out 111 | e1.printStackTrace(); 112 | } 113 | } 114 | } 115 | 116 | @Override 117 | protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 118 | doPostOrGet(req, resp); 119 | } 120 | 121 | @Override 122 | protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 123 | 124 | if(PATH_REFRESH.equals(req.getPathInfo())) { 125 | System.out.println("Refreshing index searcher"); 126 | this.searcher.refresh(); 127 | return; 128 | } 129 | 130 | doPostOrGet(req, resp); 131 | } 132 | 133 | /** 134 | * Handler function for any post or get request 135 | * 136 | * @param req 137 | * @param resp 138 | * @throws ServletException 139 | * @throws IOException 140 | */ 141 | private void doPostOrGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 142 | 143 | if (initializationError != null) { 144 | throw new ServletException("The initialization of the servlet failed: " + initializationError); 145 | } 146 | 147 | String query = RequestUtils.getStringParameter(req, PARAM_QUERY, null); 148 | String join = RequestUtils.getStringParameter(req, PARAM_JOIN, null); 149 | 150 | QuerySettings settings = new QuerySettings(queryConfig); 151 | settings.parse(req); 152 | 153 | Hashtable queryMap = createQueryMap(req, query); 154 | 155 | logger.info("Search; " + req.getQueryString() + "; " + Time.currentWallTime() + ";"); 156 | JSONObject result = searcher.search(settings, queryMap, join); 157 | 158 | if(result == null) { 159 | throw new ServletException("The index has not been created yet."); 160 | } 161 | 162 | if (settings.getFormat().equalsIgnoreCase(LookupConfig.CONFIG_FIELD_FORMAT_XML)) { 163 | 164 | resp.setCharacterEncoding("UTF-8"); 165 | resp.setContentType("application/xml"); 166 | PrintWriter out = resp.getWriter(); 167 | 168 | try { 169 | out.print(formatXml(result)); 170 | out.close(); 171 | } catch (TransformerException e) { 172 | throw new IOException(e.getMessage()); 173 | } 174 | } else { 175 | resp.setCharacterEncoding("UTF-8"); 176 | resp.setContentType("application/json"); 177 | PrintWriter out = resp.getWriter(); 178 | out.println(result.toString()); 179 | out.close(); 180 | } 181 | 182 | } 183 | 184 | private String formatXml(JSONObject result) throws TransformerException { 185 | 186 | String generatedXml = "" + XML.toString(result) + ""; 187 | 188 | if (xformer == null) { 189 | return generatedXml; 190 | } 191 | 192 | StringWriter writer = new StringWriter(); 193 | 194 | Source source = new StreamSource(new java.io.StringReader(generatedXml)); 195 | Result target = new StreamResult(writer); 196 | xformer.transform(source, target); 197 | 198 | return writer.toString(); 199 | } 200 | 201 | /** 202 | * Create a map of query fields, each field pointing to a String value (the 203 | * searched value) 204 | * 205 | * @param req 206 | * @param query 207 | * @return 208 | */ 209 | private Hashtable createQueryMap(HttpServletRequest req, String query) { 210 | 211 | Hashtable result = new Hashtable(); 212 | 213 | LookupField[] queryFields = queryConfig.getLookupFields(); 214 | 215 | for (int i = 0; i < queryFields.length; i++) { 216 | 217 | LookupField queryField = queryFields[i].copy(); 218 | 219 | String fieldRequired = req.getParameter(queryField.getName() + QUERY_SUFFIX_REQUIRED); 220 | 221 | if (fieldRequired != null) { 222 | queryField.setRequired(Boolean.parseBoolean(fieldRequired)); 223 | } 224 | 225 | String fieldExact = req.getParameter(queryField.getName() + QUERY_SUFFIX_EXACT); 226 | 227 | if (fieldExact != null) { 228 | queryField.setExact(Boolean.parseBoolean(fieldExact)); 229 | } 230 | 231 | String fieldTokenize = req.getParameter(queryField.getName() + QUERY_SUFFIX_TOKENIZE); 232 | 233 | if (fieldTokenize != null) { 234 | queryField.setTokenize(Boolean.parseBoolean(fieldTokenize)); 235 | } 236 | 237 | String fieldHighlight = req.getParameter(queryField.getName() + QUERY_SUFFIX_HIGHLIGHT); 238 | 239 | if (fieldHighlight != null) { 240 | queryField.setHighlight(Boolean.parseBoolean(fieldHighlight)); 241 | } 242 | 243 | String fieldAllowPartialMatch = req 244 | .getParameter(queryField.getName() + QUERY_SUFFIX_ALLOW_PARTIAL_MATCH); 245 | 246 | if (fieldAllowPartialMatch != null) { 247 | queryField.setAllowPartialMatch(Boolean.parseBoolean(fieldAllowPartialMatch)); 248 | } 249 | 250 | String fieldWeight = req.getParameter(queryField.getName() + QUERY_SUFFIX_WEIGHT); 251 | 252 | if (fieldWeight != null) { 253 | try { 254 | float weight = Float.parseFloat(fieldWeight); 255 | queryField.setWeight(weight); 256 | } catch (Exception e) { 257 | /* Ignore */ } 258 | } 259 | 260 | if (query != null && queryField.isQueryByDefault()) { 261 | result.put(queryField, query); 262 | } 263 | 264 | String fieldQuery = req.getParameter(queryField.getName()); 265 | 266 | if (fieldQuery != null) { 267 | try { 268 | fieldQuery = URLDecoder.decode(fieldQuery, "UTF-8"); 269 | result.put(queryField, fieldQuery); 270 | } catch (UnsupportedEncodingException e) { 271 | result.put(queryField, fieldQuery); 272 | } 273 | continue; 274 | } 275 | 276 | if (queryField.getAliases() != null) { 277 | for (String alias : queryField.getAliases()) { 278 | String aliasQuery = req.getParameter(alias); 279 | 280 | if (aliasQuery != null) { 281 | result.put(queryField, aliasQuery); 282 | break; 283 | } 284 | } 285 | } 286 | } 287 | 288 | return result; 289 | } 290 | 291 | } 292 | -------------------------------------------------------------------------------- /doc/server.md: -------------------------------------------------------------------------------- 1 | # Lookup Searcher 2 | 3 | ## About 4 | 5 | The lookup searcher is a Lucene query generator using its query builder framework. It is made accessible via a servlet that is hosted on the Lookup's jetty HTTP server. The servlet provides: 6 | 7 | * a HTML homepage with a search window 8 | * a search API at `/api/search` 9 | * an indexing API at 10 | * `/api/index/run` 11 | * `/api/index/clear` 12 | 13 | 14 | 15 | ### Example Configuration 16 | 17 | The [example configuration](../examples/lookup-config.yml) used above looks as follows 18 | 19 | ```yaml 20 | version: "1.0" 21 | indexPath: ./index 22 | maxBufferedDocs: 1000000 23 | logInterval: 1 24 | exactMatchBoost: 10 25 | prefixMatchBoost: 7 26 | fuzzyMatchBoost: 1 27 | fuzzyEditDistance: 2 28 | fuzzyPrefixLength: 2 29 | maxResults: 10000 30 | format: JSON 31 | minScore: 0.1 32 | lookupFields: 33 | - name: id 34 | weight: 10 35 | exact: true 36 | highlight: false 37 | tokenize: false 38 | queryByDefault: false 39 | - name: label 40 | weight: 1 41 | highlight: true 42 | tokenize: true 43 | allowPartialMatch: true 44 | queryByDefault: true 45 | - name: comment 46 | weight: .2 47 | highlight: true 48 | tokenize: true 49 | allowPartialMatch: true 50 | queryByDefault: true 51 | ``` 52 | 53 | The configuration holds a path to the index structure that will be used for searching along with a list of variables used for scoring results. Please refer to the [configuration documentation](#configuration) for more detailed explanations. 54 | 55 | The [queryFields](#queryfields) variable holds the most important information with a list of objects describing fields that the searcher can potentially include in the search. Each query field spefifies a field name that should be present in the index structure (as specified in the index configuration). Each field can be given default settings for score weights and other properties, such as an indicator if query inputs should be tokenized for a specific field. 56 | 57 | ## Configuration 58 | 59 | ### indexPath 60 | The index path points to the directory holding the index structure (*absolute* or *relative to the configuration file*). This is usually the folder containing the result of the lookup indexer. 61 | 62 | ### exactMatchBoost 63 | Denotes a multiplier that is applied to any result score if the search term matches a document field value exactly. Can be overriden via HTTP query parameter (e.g. `...&exactMatchBoost=100`). 64 | 65 | ### prefixMatchBoost 66 | Denotes a multiplier this is applied to any result score if the search term is a prefix of a document field value. Can be overriden via HTTP query parameter (e.g. `...&prefixMatchBoost=100`). 67 | 68 | ### fuzzyMatchBoost 69 | Denotes a multiplier this is applied to any result score if the search term roughly matches a document field value. Can be overriden via HTTP query parameter (e.g. `...&fuzzyMatchBoost=100`). 70 | 71 | ### fuzzyEditDistance 72 | Denotes the maximum edit distance between a search input and a document field such that it is still considered a fuzzy match. 73 | 74 | ### fuzzyPrefixLength 75 | This is the number of characters at the start of a term that must be identical (not fuzzy) to the query term if the query is to match that term. 76 | 77 | ### maxBufferedDocs 78 | Configuration value passed to the lucene indexer (see [setMaxBufferedDocs()](https://lucene.apache.org/core/8_1_1/core/org/apache/lucene/index/IndexWriterConfig.html#setMaxBufferedDocs-int-)). 79 | 80 | ### maxResults 81 | The maximum number of results. Can be overriden via HTTP query parameter (e.g. `...&maxResults=10`) 82 | 83 | ### format 84 | The format of the results. Defaults to [JSON](#json) and can be one of the following: 85 | 86 | #### JSON 87 | Returns the result as JSON which includes highlighting tags in matched strings. 88 | 89 | #### JSON_RAW 90 | Returns the result as JSON without any highlighting tags. 91 | 92 | #### JSON_FULL 93 | Returns the result as JSON with highlighted *and* non-highlighted strings. 94 | 95 | #### XML 96 | Returns the result as XML. 97 | 98 | ### formatTemplate 99 | When the selected format is [XML](#xml) you can provide the path to an *XSL* template to transform the result into any desired XML output. 100 | 101 | ### minScore 102 | The minimum score that a potential search result has to reach in order to be included in the result set. Can be overriden via HTTP query parameter (e.g. `...&minScore=10`). 103 | 104 | ### boostFormula 105 | *[Optional]* An mathematical function that will be applied to result documents based on any numeric field indexed to that document. 106 | 107 | ### lookupFields 108 | A list of objects describing the query fields on which the searcher will operate. The objects consist of the following subfields: 109 | 110 | #### name 111 | The name of the field. The field name can be used as a query parameter. 112 | 113 | #### type 114 | The type of the field (see [Field Types](#field-types)). 115 | 116 | #### aliases 117 | A list of strings specifying alternative names for a field name 118 | 119 | #### weight 120 | A numerical weight that is applied to a match on the respective field. E.g. can be used to express, that a match on a `title` field is worth more than a match on an `abstract` field. Can be overriden via HTTP query parameter using the field name followed by the string `Weight` (e.g. `...&labelWeight=true` when searching on the field `label`). 121 | 122 | #### highlight 123 | Denotes whether the result should include special html tags highlighting the match between the query string and the field value. Defaults to `false`. Can be overriden via HTTP query parameter using the field name followed by the string `Highlight` (e.g. `...&labelHighlight=true` when searching on the field `label`). 124 | 125 | #### tokenize 126 | If `true`, the query string will be tokenized and each token will be matched against the field value of this field. Tokenization includes, for instance, splitting of input strings by whitespaces. If set to `false`, the input will be matched against the document fields as is. Defaults to `false`. Can be overriden via HTTP query parameter using the field name followed by the string `Tokenize` (e.g. `...&labelTokenize=true` when searching on the field `label`). 127 | 128 | #### required 129 | If `true`, a match on this field is required. A document that has a match on any other field included in the search but does *not* have a match on this field, will be dropped from the result set even if it would have been included otherwise. Defaults to `false`. Can be overriden via HTTP query parameter using the field name followed by the string `Required` (e.g. `...&labelRequired=true` when searching on the field `label`). 130 | 131 | #### exact 132 | If `true`, a match on this field only counts if the field value matches the query string exactly. In that case, fuzzy and prefix matching will not be applied. Defaults to `false`. Can be overriden via HTTP query parameter using the field name followed by the string `Exact` (e.g. `...&labelExact=true` when searching on the field `label`). 133 | 134 | #### allowPartialMatch 135 | Before matching against a field, the query string can be [tokenized](#tokenize). If [allowPartialMatch](#allowpartialmatch) is set to `false`, a field will only count as matched if all query tokens match the field. If `true`, the field will match if at least one query token matches the field. Can be overriden via HTTP query parameter using the field name followed by the string `AllowPartialMatch` (e.g. `...&labelAllowPartialMatch=true` when searching on the field `label`). 136 | 137 | #### queryByDefault 138 | If `true`, all queries sent with the [query](#query) parameter will be matched against this field. 139 | 140 | ## Query Parameters 141 | 142 | ### query 143 | The most important parameter: the search query string. The query string will be matched against all fields configured as [queryByDefault](#querybydefault). 144 | 145 | ### [fieldName] 146 | Any configured field name can be used as a query parameter. The string specified with this parameter will only be matched against the respective field. 147 | 148 | ### [fieldName]Weight 149 | Float value. See [weight](#weight). 150 | 151 | ### [fieldName]Exact 152 | Boolean value. See [exact](#exact). 153 | 154 | ### [fieldName]Required 155 | Boolean value. See [required](#required). 156 | 157 | ### [fieldName]AllowPartialMatch 158 | Boolean value. See [allowPartialMatch](#allowpartialmatch). 159 | 160 | ### [fieldName]Tokenize 161 | Boolean value. See [tokenize](#tokenize). 162 | 163 | ### [fieldName]Highlight 164 | Boolean value. See [highlight](#highlight). 165 | 166 | ### join 167 | Join can specify any indexed field. The search will then be executed normally but the initial result set will not be returned. Instead, Lucene will return all documents that have a value for the specified field equal to any document id in the initial result set (simplified Lucene join). 168 | 169 | ### exactMatchBoost 170 | Float value. See [exactMatchBoost](#exactmatchboost) 171 | 172 | ### prefixMatchBoost 173 | Float value. See [prefixMatchBoost](#prefixmatchboost) 174 | 175 | ### fuzzyMatchBoost 176 | Float value. See [fuzzyMatchBoost](#fuzzymatchboost) 177 | 178 | ### fuzzyEditDistance 179 | Int value. See [fuzzyEditDistance](#fuzzyeditdistance) 180 | 181 | ### fuzzyPrefixLength 182 | Int value. See [fuzzyPrefixLength](#fuzzyprefixlength) 183 | 184 | ### maxResults 185 | See [maxResults](#maxresults) 186 | 187 | ### format 188 | See [format](#format) 189 | 190 | ## Field Types 191 | When indexing and searching it is sometimes important to explicitly set the type of a field. This will keep the indexer from tokenizing URIs or allow it to run min/max queries on numeric values. 192 | The field type can be set to the following values: 193 | 194 | ### text 195 | The field will be indexed and tokenized, which is useful for indexing any text with multiple words. Search queries can then return matches for each word. 196 | 197 | ### uri 198 | The field will be indexed but *not* tokenized or changed in any way. Useful for uris or other identifiers that should only match in its entirety. Uses the [UriAnalzyer](./src/main/java/org/dbpedia/lookup/indexer/UriAnalyzer.java). 199 | 200 | ### string 201 | The field will be indexed but *not* tokenized. The field value will be indexed in its *lowercase* form. [StringPhraseAnalyzer](./src/main/java/org/dbpedia/lookup/indexer/StringPhraseAnalyzer.java). 202 | 203 | ### stored 204 | Creates a field that is stored but not indexed. No changes to the string are applied. 205 | 206 | ### ngram 207 | Uses the [NGramAnalyzer](./src/main/java/org/dbpedia/lookup/indexer/NGramAnalyzer.java) to tokenize strings into ngrams of lengths between 3 and 5 characters. 208 | 209 | ### numeric 210 | Saves the file as a numeric field. Numeric field can be used in arithmetic operations during query time. Additionally, numeric fields can be included as variables in the global boost formula 211 | 212 | -------------------------------------------------------------------------------- /lookup/src/main/java/org/dbpedia/lookup/Main.java: -------------------------------------------------------------------------------- 1 | package org.dbpedia.lookup; 2 | 3 | import org.apache.commons.cli.CommandLine; 4 | import org.apache.commons.cli.CommandLineParser; 5 | import org.apache.commons.cli.DefaultParser; 6 | import org.apache.commons.cli.Options; 7 | import org.apache.lucene.analysis.Analyzer; 8 | import org.apache.lucene.analysis.miscellaneous.PerFieldAnalyzerWrapper; 9 | import org.apache.lucene.analysis.standard.StandardAnalyzer; 10 | import org.apache.lucene.index.IndexWriter; 11 | import org.apache.lucene.index.IndexWriterConfig; 12 | import org.apache.lucene.store.FSDirectory; 13 | import org.dbpedia.lookup.config.LookupConfig; 14 | import org.dbpedia.lookup.config.LookupField; 15 | import org.dbpedia.lookup.indexer.LookupIndexer; 16 | import org.dbpedia.lookup.indexer.NGramAnalyzer; 17 | import org.dbpedia.lookup.indexer.StringPhraseAnalyzer; 18 | import org.dbpedia.lookup.indexer.UriAnalyzer; 19 | import org.dbpedia.lookup.searcher.LookupSearcher; 20 | import org.dbpedia.lookup.server.LookupIndexerServlet; 21 | import org.dbpedia.lookup.server.LookupSearcherServlet; 22 | import org.eclipse.jetty.server.Handler; 23 | import org.eclipse.jetty.server.Server; 24 | import org.eclipse.jetty.server.handler.HandlerList; 25 | import org.eclipse.jetty.servlet.DefaultServlet; 26 | import org.eclipse.jetty.servlet.FilterHolder; 27 | import org.eclipse.jetty.servlet.ServletContextHandler; 28 | import org.eclipse.jetty.servlet.ServletHolder; 29 | import org.eclipse.jetty.servlets.CrossOriginFilter; 30 | import org.slf4j.Logger; 31 | import org.slf4j.LoggerFactory; 32 | 33 | import jakarta.servlet.DispatcherType; 34 | 35 | import java.io.File; 36 | import java.io.IOException; 37 | import java.nio.file.Paths; 38 | import java.util.EnumSet; 39 | import java.util.HashMap; 40 | import java.util.Map; 41 | 42 | /** 43 | * Run to start a jetty server that hosts the lookup servlet and makes it 44 | * accessible 45 | * via HTTP 46 | */ 47 | public class Main { 48 | 49 | final static Logger logger = LoggerFactory.getLogger(LookupIndexerServlet.class); 50 | 51 | public static final String CONFIG_PATH = "configpath"; 52 | 53 | private static final String CLI_OPT_CONFIG = "c"; 54 | 55 | private static final String CLI_OPT_CONFIG_LONG = "config"; 56 | 57 | private static final String CLI_OPT_CONFIG_HELP = "The path of the application configuration file."; 58 | 59 | private static final String CLI_OPT_HOME = "h"; 60 | 61 | private static final String CLI_OPT_HOME_LONG = "home"; 62 | 63 | private static final String CLI_OPT_HOME_HELP = "The path of the index.html"; 64 | 65 | private static final String CLI_OPT_PORT = "p"; 66 | 67 | private static final String CLI_OPT_PORT_LONG = "port"; 68 | 69 | private static final String CLI_OPT_PORT_HELP = "The port that will be used to access the lookup servlet"; 70 | 71 | private static Server server; 72 | 73 | private static Logger log; 74 | 75 | /** 76 | * Run to start a jetty server that hosts the lookup servlet and makes it 77 | * accessible 78 | * via HTTP 79 | * 80 | * @param args 81 | * @throws Exception 82 | */ 83 | public static void main(String[] args) throws Exception { 84 | 85 | log = LoggerFactory.getLogger(Server.class); 86 | String configPath = null; 87 | String resourceBasePath = null; 88 | int port = 8082; 89 | 90 | Options options = new Options(); 91 | options.addOption(CLI_OPT_CONFIG, CLI_OPT_CONFIG_LONG, true, CLI_OPT_CONFIG_HELP); 92 | options.addOption(CLI_OPT_HOME, CLI_OPT_HOME_LONG, true, CLI_OPT_HOME_HELP); 93 | options.addOption(CLI_OPT_PORT, CLI_OPT_PORT_LONG, true, CLI_OPT_PORT_HELP); 94 | 95 | CommandLineParser cmdParser = new DefaultParser(); 96 | 97 | try { 98 | 99 | CommandLine cmd = cmdParser.parse(options, args); 100 | 101 | if (cmd.hasOption(CLI_OPT_CONFIG)) { 102 | configPath = cmd.getOptionValue(CLI_OPT_CONFIG); 103 | } 104 | 105 | if (cmd.hasOption(CLI_OPT_HOME)) { 106 | resourceBasePath = cmd.getOptionValue(CLI_OPT_HOME); 107 | } 108 | 109 | if (cmd.hasOption(CLI_OPT_PORT)) { 110 | String portString = cmd.getOptionValue(CLI_OPT_PORT); 111 | port = Integer.parseInt(portString); 112 | } 113 | 114 | } catch (org.apache.commons.cli.ParseException e1) { 115 | e1.printStackTrace(); 116 | } 117 | 118 | if (configPath == null) { 119 | log.error("No config specified"); 120 | return; 121 | } 122 | LookupConfig lookupConfig = null; 123 | 124 | try { 125 | lookupConfig = LookupConfig.Load(configPath); 126 | } catch (Exception e) { 127 | log.error("Unable to load the config file:"); 128 | log.error(e.getMessage()); 129 | return; 130 | } 131 | 132 | if (resourceBasePath == null) { 133 | File configFile = new File(configPath); 134 | resourceBasePath = configFile.getParent().toString(); 135 | } 136 | 137 | IndexWriterConfig indexWriterConfig = new IndexWriterConfig(createAnalyzer(lookupConfig)); 138 | indexWriterConfig.setOpenMode(IndexWriterConfig.OpenMode.CREATE_OR_APPEND); 139 | indexWriterConfig.setMaxBufferedDocs(lookupConfig.getMaxBufferedDocs()); 140 | 141 | String indexPath = lookupConfig.getIndexPath(); 142 | File indexFile = new File(indexPath); 143 | 144 | if (!indexFile.isAbsolute()) { 145 | 146 | lookupConfig.setIndexPath(indexFile.getAbsolutePath()); 147 | } 148 | 149 | File file = new File(indexPath); 150 | file.mkdirs(); 151 | 152 | FSDirectory targetDirectory = FSDirectory.open(Paths.get(indexPath)); 153 | 154 | IndexWriter indexWriter = new IndexWriter(targetDirectory, indexWriterConfig); 155 | LookupIndexer indexer = new LookupIndexer(logger, lookupConfig, indexWriter); 156 | LookupSearcher searcher = new LookupSearcher(lookupConfig); 157 | 158 | server = new Server(port); 159 | 160 | // Take care of CORS requests 161 | ServletContextHandler context = new ServletContextHandler(); 162 | 163 | context.setAttribute("INDEXER", indexer); 164 | context.setAttribute("SEARCHER", searcher); 165 | 166 | context.setContextPath("/"); 167 | context.setWelcomeFiles(new String[] { "index.html" }); 168 | context.setResourceBase(resourceBasePath); 169 | 170 | FilterHolder cors = context.addFilter(CrossOriginFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST)); 171 | cors.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM, "*"); 172 | cors.setInitParameter(CrossOriginFilter.ACCESS_CONTROL_ALLOW_ORIGIN_HEADER, "*"); 173 | cors.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM, "GET,POST,HEAD"); 174 | cors.setInitParameter(CrossOriginFilter.ALLOWED_HEADERS_PARAM, "X-Requested-With,Content-Type,Accept,Origin"); 175 | 176 | // Create a servlet handler and holder for the API and pass the config 177 | ServletHolder searchServletHolder = context.addServlet(LookupSearcherServlet.class, "/api/search/*"); 178 | searchServletHolder.setInitParameter(CONFIG_PATH, configPath); 179 | 180 | // Create a servlet handler and holder for the API and pass the config 181 | ServletHolder indexServletHolder = context.addServlet(LookupIndexerServlet.class, "/api/index/*"); 182 | indexServletHolder.setInitParameter(CONFIG_PATH, configPath); 183 | 184 | ServletHolder def = new ServletHolder("default", DefaultServlet.class); 185 | def.setInitParameter("resourceBase", resourceBasePath); 186 | def.setInitParameter("dirAllowed", "false"); 187 | context.addServlet(def, "/"); 188 | 189 | // Add handlers for the index html and the API servlet 190 | HandlerList handlers = new HandlerList(); 191 | handlers.setHandlers(new Handler[] { context }); 192 | server.setHandler(handlers); 193 | server.start(); 194 | 195 | boolean running = true; 196 | 197 | while (running) { 198 | Thread.sleep(1000); 199 | continue; 200 | } 201 | 202 | log.info("EXITING. STOPPING SERVER."); 203 | server.stop(); 204 | } 205 | 206 | /** 207 | * Creates a watch service that watches for changes in the index directory. Any 208 | * change in the index 209 | * structure will trigger a restart of the jetty server and thus a refresh of 210 | * the index searcher. 211 | * 212 | * @param configPath 213 | * @throws Exception 214 | * @throws IOException 215 | * @throws InterruptedException 216 | 217 | private static void watchIndex(String configPath) throws Exception, IOException, InterruptedException { 218 | LookupConfig queryConfig = LookupConfig.Load(configPath); 219 | 220 | WatchService watcher = FileSystems.getDefault().newWatchService(); 221 | 222 | File indexDirectoryFile = new File(queryConfig.getIndexPath()); 223 | indexDirectoryFile.mkdirs(); 224 | 225 | Path indexDirectory = Paths.get(queryConfig.getIndexPath()); 226 | indexDirectory.register(watcher, 227 | StandardWatchEventKinds.ENTRY_CREATE, 228 | StandardWatchEventKinds.ENTRY_MODIFY); 229 | 230 | while (true) { 231 | 232 | Thread.sleep(1000); 233 | WatchKey key = watcher.poll(); 234 | 235 | if (key == null) { 236 | continue; 237 | } 238 | 239 | for (WatchEvent event : key.pollEvents()) { 240 | WatchEvent.Kind kind = event.kind(); 241 | 242 | if (kind == StandardWatchEventKinds.OVERFLOW) { 243 | continue; 244 | } 245 | 246 | server.stop(); 247 | server.start(); 248 | break; 249 | } 250 | 251 | if (!key.isValid()) { 252 | log.info("key is INVALID!"); 253 | } 254 | 255 | key.reset(); 256 | } 257 | 258 | } */ 259 | 260 | private static Analyzer createAnalyzer(LookupConfig config) { 261 | 262 | Map analyzerPerField = new HashMap(); 263 | 264 | for (LookupField field : config.getLookupFields()) { 265 | 266 | String fieldType = field.getType(); 267 | 268 | if (fieldType == null) { 269 | continue; 270 | } 271 | 272 | if (fieldType.contentEquals(Constants.CONFIG_FIELD_TYPE_STRING)) { 273 | analyzerPerField.put(field.getName(), new StringPhraseAnalyzer()); 274 | } 275 | 276 | if(fieldType.contentEquals(Constants.CONFIG_FIELD_TYPE_NGRAM)) { 277 | analyzerPerField.put(field.getName(), new NGramAnalyzer()); 278 | } 279 | 280 | if(fieldType.contentEquals(Constants.CONFIG_FIELD_TYPE_URI)) { 281 | analyzerPerField.put(field.getName(), new UriAnalyzer()); 282 | } 283 | } 284 | 285 | Analyzer analyzer = new PerFieldAnalyzerWrapper(new StandardAnalyzer(), analyzerPerField); 286 | return analyzer; 287 | } 288 | } 289 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2021 DBpedia 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /lookup/src/main/java/org/dbpedia/lookup/indexer/LuceneIndexWriter.java: -------------------------------------------------------------------------------- 1 | package org.dbpedia.lookup.indexer; 2 | 3 | import java.io.IOException; 4 | import java.util.concurrent.ConcurrentHashMap; 5 | 6 | import org.apache.jena.query.QuerySolution; 7 | import org.apache.jena.query.ResultSet; 8 | import org.apache.jena.rdf.model.RDFNode; 9 | import org.apache.lucene.document.Document; 10 | import org.apache.lucene.document.StringField; 11 | import org.apache.lucene.document.TextField; 12 | import org.apache.lucene.document.Field; 13 | import org.apache.lucene.document.LongPoint; 14 | import org.apache.lucene.document.NumericDocValuesField; 15 | import org.apache.lucene.document.SortedDocValuesField; 16 | import org.apache.lucene.document.SortedSetDocValuesField; 17 | import org.apache.lucene.document.StoredField; 18 | import org.apache.lucene.index.DirectoryReader; 19 | import org.apache.lucene.index.IndexWriter; 20 | import org.apache.lucene.index.IndexableField; 21 | import org.apache.lucene.index.StoredFields; 22 | import org.apache.lucene.index.Term; 23 | import org.apache.lucene.search.IndexSearcher; 24 | import org.apache.lucene.search.ScoreDoc; 25 | import org.apache.lucene.search.TermQuery; 26 | import org.apache.lucene.search.TopDocs; 27 | import org.apache.lucene.util.BytesRef; 28 | import org.dbpedia.lookup.Constants; 29 | import org.dbpedia.lookup.config.IndexField; 30 | import org.dbpedia.lookup.config.LookupConfig; 31 | import org.dbpedia.lookup.config.LookupField; 32 | import org.slf4j.Logger; 33 | 34 | public class LuceneIndexWriter { 35 | 36 | private IndexWriter indexWriter; 37 | 38 | private IndexSearcher searcher; 39 | 40 | private Logger logger; 41 | 42 | private ConcurrentHashMap documentCache; 43 | 44 | private String lastDocument = null; 45 | 46 | private String lastValue = null; 47 | 48 | private LookupConfig config; 49 | 50 | 51 | public LuceneIndexWriter(Logger logger, IndexWriter indexWriter, LookupConfig config) throws IOException { 52 | 53 | this.logger = logger; 54 | this.indexWriter = indexWriter; 55 | this.config = config; 56 | 57 | // Create a document cache to keep documents in between commits to the lucene structure 58 | documentCache = new ConcurrentHashMap(); 59 | // Create the writer and searcher 60 | try { 61 | searcher = new IndexSearcher(DirectoryReader.open(indexWriter.getDirectory())); 62 | } catch(IOException exception) { 63 | searcher = null; 64 | } 65 | } 66 | 67 | /* 68 | public LuceneIndexWriter(IndexConfig indexConfig, Logger logger) { 69 | 70 | this.logger = logger; 71 | this.indexConfig = indexConfig; 72 | this.targetPath = indexConfig.getIndexPath(); 73 | 74 | // Create a document cache to keep documents in between commits to the lucene structure 75 | documentCache = new ConcurrentHashMap(); 76 | 77 | 78 | try { 79 | // Open the target directory 80 | targetDirectory = FSDirectory.open(Paths.get(targetPath)); 81 | 82 | File file = new File(this.indexPath); 83 | file.mkdirs(); 84 | 85 | } catch (IndexNotFoundException e) { 86 | return; 87 | } catch (IOException e) { 88 | cleanUp(); 89 | e.printStackTrace(); 90 | return; 91 | } 92 | } */ 93 | 94 | /* 95 | public void purge() { 96 | try { 97 | indexWriter.close(); 98 | // Remove lock file 99 | File lockFile = new File(indexPath + lockFileName); 100 | lockFile.delete(); 101 | 102 | File targetFile = new File(indexPath); 103 | FileUtils.cleanDirectory(targetFile); 104 | 105 | 106 | indexWriter = new IndexWriter(indexDirectory, createWriterConfig(maxBufferedDocs)); 107 | searcher = new IndexSearcher(DirectoryReader.open(indexDirectory)); 108 | 109 | } catch (IOException e) { 110 | e.printStackTrace(); 111 | } 112 | }*/ 113 | 114 | public void clear() { 115 | try { 116 | // DELETUS! 117 | indexWriter.deleteAll(); 118 | // Commit the changes 119 | commit(); 120 | } catch (IOException e) { 121 | e.printStackTrace(); 122 | } 123 | 124 | } 125 | 126 | public void indexResult(ResultSet result, IndexField path) { 127 | 128 | int k = 0; 129 | 130 | while (result.hasNext()) { 131 | 132 | QuerySolution entry = result.next(); 133 | RDFNode documentNode = entry.get(path.getDocumentVariable()); 134 | RDFNode fieldValueNode = entry.get(path.getFieldName()); 135 | 136 | lastDocument = documentNode.toString(); 137 | 138 | if (fieldValueNode.isLiteral()) { 139 | lastValue = fieldValueNode.asLiteral().getString(); 140 | } else { 141 | lastValue = fieldValueNode.toString(); 142 | } 143 | 144 | indexField(lastDocument, path, lastValue); 145 | 146 | if(config.getLogInterval() == 0) { 147 | logger.info("Binding " + k + ": [" + lastDocument + "] -> \"" + lastValue + "\""); 148 | } else if (k % config.getLogInterval() == 0) { 149 | logger.info("Binding " + k + ": [" + lastDocument + "] -> \"" + lastValue + "\""); 150 | } 151 | 152 | k++; 153 | } 154 | } 155 | 156 | public void indexField(String documentId, IndexField indexField, String valueString) { 157 | 158 | String field = indexField.getFieldName(); 159 | String fieldType = indexField.getType(); 160 | 161 | if (fieldType != null) { 162 | fieldType = fieldType.toLowerCase(); 163 | } else { 164 | 165 | LookupField lookupField = config.getLookupField(field); 166 | 167 | if(lookupField != null && lookupField.getType() != null) { 168 | fieldType = lookupField.getType(); 169 | } else { 170 | fieldType = Constants.CONFIG_FIELD_TYPE_TEXT; 171 | } 172 | } 173 | 174 | try { 175 | Document doc = findDocument(documentId); 176 | 177 | if(valueString != null) { 178 | IndexableField[] existingFields = doc.getFields(field); 179 | 180 | for(IndexableField existingField : existingFields) { 181 | if(existingField != null && valueString.equals(existingField.stringValue())) { 182 | return; 183 | } 184 | } 185 | } 186 | 187 | switch (fieldType) { 188 | case Constants.CONFIG_FIELD_TYPE_NUMERIC: 189 | long value = Long.parseLong(valueString); 190 | doc.removeFields(field); 191 | doc.add(new StoredField(field, value)); 192 | doc.add(new LongPoint(field, value)); 193 | doc.add(new NumericDocValuesField(field, value)); 194 | break; 195 | case Constants.CONFIG_FIELD_TYPE_STORED: 196 | doc.add(new StoredField(field, valueString)); 197 | break; 198 | case Constants.CONFIG_FIELD_TYPE_STRING: 199 | doc.add(new StringField(field, valueString, Field.Store.YES)); 200 | break; 201 | case Constants.CONFIG_FIELD_TYPE_STORED_SORTED: 202 | doc.add(new StoredField(field, valueString)); 203 | doc.add(new SortedSetDocValuesField(field, new BytesRef(valueString))); 204 | break; 205 | case Constants.CONFIG_FIELD_TYPE_URI: 206 | doc.add(new StringField(field, valueString, Field.Store.YES)); 207 | break; 208 | default: 209 | doc.add(new TextField(field, valueString, Field.Store.YES)); 210 | break; 211 | } 212 | 213 | indexWriter.updateDocument(new Term(Constants.FIELD_DOCUMENT_ID, documentId), doc); 214 | 215 | } catch (IOException e) { 216 | e.printStackTrace(); 217 | } 218 | } 219 | 220 | private Document findDocument(String documentId) throws IOException { 221 | 222 | if(documentId == null) { 223 | return null; 224 | } 225 | 226 | if (documentCache.containsKey(documentId)) { 227 | return documentCache.get(documentId); 228 | } 229 | 230 | // First try: search the index 231 | Document document = getDocumentFromIndex(documentId); 232 | 233 | if (document == null) { 234 | // Second try: create new document 235 | document = new Document(); 236 | 237 | document.add(new StringField(Constants.FIELD_DOCUMENT_ID, documentId, Field.Store.YES)); 238 | document.add(new SortedDocValuesField(Constants.FIELD_DOCUMENT_ID, new BytesRef(documentId))); 239 | } 240 | 241 | // we touched the document, we might touch it again soon -> add to cache 242 | documentCache.put(documentId, document); 243 | return document; 244 | } 245 | 246 | private Document getDocumentFromIndex(String documentId) throws IOException { 247 | 248 | if (searcher == null) { 249 | return null; 250 | } 251 | 252 | Term documentIdTerm = new Term(Constants.FIELD_DOCUMENT_ID, documentId); 253 | TermQuery documentIdTermQuery = new TermQuery(documentIdTerm); 254 | 255 | TopDocs docs = searcher.search(documentIdTermQuery, 1); 256 | StoredFields storedFields = searcher.storedFields(); 257 | 258 | if (docs.scoreDocs.length > 0) { 259 | 260 | ScoreDoc scoreDoc = docs.scoreDocs[0]; 261 | Document document = storedFields.document(scoreDoc.doc); 262 | 263 | document.removeFields(Constants.FIELD_DOCUMENT_ID); 264 | document.add(new StringField(Constants.FIELD_DOCUMENT_ID, documentId, Field.Store.YES)); 265 | document.add(new SortedDocValuesField(Constants.FIELD_DOCUMENT_ID, new BytesRef(documentId))); 266 | 267 | // Fetched document fields are all reset to default stored/text fields 268 | // Special fields such as the numeric fields have to be reset to their 269 | // respective type 270 | for (LookupField field : config.getLookupFields()) { 271 | 272 | String fieldType = field.getType(); 273 | 274 | if (fieldType == null) { 275 | continue; 276 | } 277 | 278 | if(fieldType.contentEquals(Constants.CONFIG_FIELD_TYPE_STORED_SORTED)) { 279 | IndexableField[] storedSortedFields = document.getFields(field.getName()); 280 | String fieldName = field.getName(); 281 | document.removeFields(fieldName); 282 | 283 | for(IndexableField storedField : storedSortedFields) { 284 | String value = storedField.stringValue(); 285 | // Re-add the field 286 | document.add(new StoredField(fieldName, value)); 287 | document.add(new SortedSetDocValuesField(fieldName, new BytesRef(value))); 288 | } 289 | 290 | } 291 | 292 | // Remove all numeric index fields and re-add them to the document as 293 | // NumericDocValuesField (plus StoredField for retrieval) 294 | if (fieldType.contentEquals(Constants.CONFIG_FIELD_TYPE_NUMERIC)) { 295 | 296 | // Fetch the field with the given index field name (does not support 297 | // multi-values) 298 | IndexableField numericField = document.getField(field.getName()); 299 | 300 | // Only do this if a field with the given field name exists 301 | if (numericField != null) { 302 | 303 | // Fetch the field long value 304 | long value = numericField.numericValue().longValue(); 305 | 306 | // Remove all fields with the respective name 307 | document.removeFields(field.getName()); 308 | 309 | // Re-add the field 310 | document.add(new NumericDocValuesField(field.getName(), value)); 311 | document.add(new StoredField(field.getName(), value)); 312 | document.add(new LongPoint(field.getName(), value)); 313 | } 314 | } 315 | } 316 | 317 | return document; 318 | } 319 | 320 | return null; 321 | } 322 | 323 | public void commit() { 324 | 325 | 326 | logger.info("=== COMMITING ==="); 327 | 328 | try { 329 | indexWriter.commit(); 330 | 331 | documentCache = new ConcurrentHashMap(); 332 | searcher = new IndexSearcher(DirectoryReader.open(indexWriter.getDirectory())); 333 | System.gc(); 334 | 335 | } catch (IOException e) { 336 | e.printStackTrace(); 337 | } 338 | 339 | } 340 | 341 | public void finish() { 342 | 343 | } 344 | 345 | public void test() { 346 | 347 | } 348 | 349 | /** 350 | * Drops documents from the index based on the specified values. 351 | * 352 | * @param values An array of URIs representing the documents to drop from the index. 353 | */ 354 | public void drop(String[] values) { 355 | if (values == null || values.length == 0) { 356 | logger.info("No values provided for drop operation."); 357 | return; 358 | } 359 | 360 | try { 361 | for (String value : values) { 362 | logger.info("Dropping document with value: " + value); 363 | 364 | // Create a term query to find the document by the FIELD_DOCUMENT_ID 365 | Term term = new Term(Constants.FIELD_DOCUMENT_ID, value); 366 | indexWriter.deleteDocuments(term); 367 | } 368 | 369 | // Commit the changes to the index 370 | commit(); 371 | logger.info("Drop operation completed successfully."); 372 | 373 | } catch (IOException e) { 374 | logger.error("An error occurred while dropping documents from the index.", e); 375 | } 376 | } 377 | 378 | } 379 | -------------------------------------------------------------------------------- /lookup/src/main/java/org/dbpedia/lookup/indexer/LookupIndexer.java: -------------------------------------------------------------------------------- 1 | package org.dbpedia.lookup.indexer; 2 | 3 | import java.io.File; 4 | import java.io.IOException; 5 | import java.util.concurrent.TimeUnit; 6 | 7 | import org.apache.jena.query.ARQ; 8 | import org.apache.jena.query.Dataset; 9 | import org.apache.jena.query.DatasetFactory; 10 | import org.apache.jena.query.Query; 11 | import org.apache.jena.query.QueryExecution; 12 | import org.apache.jena.query.QueryExecutionFactory; 13 | import org.apache.jena.query.QueryFactory; 14 | import org.apache.jena.query.ReadWrite; 15 | import org.apache.jena.query.ResultSet; 16 | import org.apache.jena.rdfconnection.RDFConnection; 17 | import org.apache.jena.rdfconnection.RDFConnectionFactory; 18 | import org.apache.jena.sparql.core.DatasetGraph; 19 | import org.apache.jena.system.Txn; 20 | import org.apache.jena.tdb2.DatabaseMgr; 21 | import org.apache.jena.tdb2.loader.DataLoader; 22 | import org.apache.jena.tdb2.loader.LoaderFactory; 23 | import org.apache.jena.tdb2.loader.base.MonitorOutput; 24 | import org.apache.lucene.index.IndexWriter; 25 | import org.dbpedia.lookup.DatabusUtils; 26 | import org.dbpedia.lookup.RDFFileFilter; 27 | import org.dbpedia.lookup.config.IndexConfig; 28 | import org.dbpedia.lookup.config.IndexField; 29 | import org.dbpedia.lookup.config.LookupConfig; 30 | import org.slf4j.Logger; 31 | 32 | /** 33 | * The main class for index creation 34 | * 35 | * @author Jan Forberg 36 | * 37 | */ 38 | public class LookupIndexer { 39 | 40 | private Logger logger; 41 | 42 | private LuceneIndexWriter indexWriter; 43 | 44 | private static final String VALUES_PLACEHOLDER_STRING = "#VALUES#"; 45 | 46 | private static final String VALUES_CLAUSE_TEMPLATE = "VALUES ?%1$s { %2$s }"; 47 | 48 | public static final String ERROR_INVALID_INDEX_MODE = "Unkown specified index mode, exiting. Use either BUILD_MEM, BUILD_DISK, INDEX_DISK or INDEX_SPARQL_ENDPOINT."; 49 | 50 | public LookupIndexer(Logger logger, LookupConfig config, IndexWriter indexWriter) throws IOException { 51 | this.logger = logger; 52 | this.indexWriter = new LuceneIndexWriter(logger, indexWriter, config); 53 | } 54 | 55 | public LookupIndexer(Logger logger, IndexConfig config) { 56 | this.logger = logger; 57 | // indexWriter = new LuceneIndexWriter(logger, config.getIndexPath(), config.getMaxBufferedDocs()); 58 | } 59 | 60 | public void run(IndexConfig config, String[] values) throws IOException { 61 | 62 | try { 63 | // Update queries based on URIs specified in the CLI 64 | updateQueriesForResources(values, config); 65 | 66 | // Initialize ARQ 67 | ARQ.init(); 68 | 69 | // Switch over the index mode to execute on of the following methods: 70 | switch (config.getIndexMode()) { 71 | case INDEX_IN_MEMORY: 72 | indexInMemory(config); 73 | break; 74 | case BUILD_AND_INDEX_ON_DISK: 75 | buildDisk(config); 76 | break; 77 | case INDEX_ON_DISK: 78 | indexDisk(config); 79 | break; 80 | case INDEX_SPARQL_ENDPOINT: 81 | indexSparqlEndpoint(config); 82 | break; 83 | } 84 | 85 | indexWriter.commit(); 86 | indexWriter.finish(); 87 | 88 | } catch (Exception e) { 89 | throw (e); 90 | } 91 | } 92 | 93 | public void clear() { 94 | indexWriter.clear(); 95 | } 96 | 97 | public Logger getLogger() { 98 | return logger; 99 | } 100 | 101 | /** 102 | * If one or more resources are specified via the CLI, all queries will be 103 | * updated to only 104 | * query for key-value pairs for those specific resources. This is achived by 105 | * inserting a 106 | * VALUES clause into each query which restricts the key to the set of specified 107 | * URIs 108 | * 109 | * @param resourceURI 110 | * @param indexConfig 111 | */ 112 | private void updateQueriesForResources(String[] values, final IndexConfig indexConfig) { 113 | // Create the values string. Any occurance of the the string %VALUES% will be 114 | // replaced 115 | // with the values string before querying 116 | String valuesURIString = ""; 117 | 118 | // The values string will be created from the whitespace separated URIs passed 119 | // as the 120 | // resourceURI argument (-r) 121 | if (values != null) { 122 | 123 | for (int i = 0; i < values.length; i++) { 124 | valuesURIString += "<" + values[i] + "> "; 125 | } 126 | } 127 | 128 | for (IndexField field : indexConfig.getIndexFields()) { 129 | String query = field.getQuery(); 130 | String resourceName = field.getDocumentVariable(); 131 | String valuesClause = ""; 132 | 133 | if (values != null) { 134 | valuesClause = String.format(VALUES_CLAUSE_TEMPLATE, resourceName, valuesURIString); 135 | } 136 | 137 | query = query.replace(VALUES_PLACEHOLDER_STRING, valuesClause); 138 | logger.info("Updated Query: " + query); 139 | field.setQuery(query); 140 | } 141 | } 142 | 143 | /** 144 | * Drops documents from the index based on the specified values. 145 | * 146 | * @param values An array of URIs representing the documents to drop from the index. 147 | */ 148 | public void drop(String[] values) { 149 | indexWriter.drop(values); 150 | } 151 | 152 | /** 153 | * Indexing based on an already existing SPARQL endpoint 154 | */ 155 | private void indexSparqlEndpoint(IndexConfig config) { 156 | 157 | 158 | // Iterate over all index fields 159 | for (IndexField indexFieldConfig : config.getIndexFields()) { 160 | 161 | logger.info("====================================================================="); 162 | logger.info("Indexing field '" + indexFieldConfig.getFieldName() + "'"); 163 | logger.info("====================================================================="); 164 | 165 | try (QueryExecution qexec = QueryExecutionFactory.sparqlService(config.getSparqlEndpoint(), 166 | indexFieldConfig.getQuery())) { 167 | 168 | // Query endpoint and get results (key-value pairs) 169 | org.apache.jena.query.ResultSet results = qexec.execSelect(); 170 | 171 | // Send to indexer 172 | indexWriter.indexResult(results, indexFieldConfig); 173 | } 174 | } 175 | 176 | } 177 | 178 | /** 179 | * Creates the index by building an Apache Jena dataset in memory. 180 | * Once the dataset is built, the indexable key-value pairs are fetched via 181 | * SPARQL queries and sent to the Lucene indexer. This method is only 182 | * recommended for indexing smaller files 183 | * as it uses a considerable amount of RAM 184 | * 185 | * @param dataPath The path of the data to load 186 | * @param cleanIndex Indicates whether to delete any existing Lucene index in 187 | * the target folder before indexing 188 | * @param xmlConfig The configuration file used for indexing 189 | */ 190 | private void indexInMemory(IndexConfig config) { 191 | Dataset dataset = DatasetFactory.create(); 192 | 193 | // Find the files to load in the specified data path 194 | File[] filesToLoad = getFilesToLoad(config); 195 | 196 | if (filesToLoad == null || filesToLoad.length == 0) { 197 | logger.info("Nothing to load. Exiting."); 198 | return; 199 | } 200 | 201 | logger.info("====================================================================="); 202 | logger.info("Loading Files to In-Memory TDB2 Database"); 203 | logger.info("====================================================================="); 204 | 205 | // Load to in-memory triple store 206 | try (RDFConnection conn = RDFConnectionFactory.connect(dataset)) { 207 | for (File file : filesToLoad) { 208 | logger.info("Loading file " + file.getPath() + "..."); 209 | conn.load(file.getPath()); 210 | } 211 | } 212 | 213 | indexData(dataset, config); 214 | } 215 | 216 | /** 217 | * Creates the index by building a TDB2 data set on disk using a parallel bulk 218 | * loader. 219 | * Once the data set is build, the indexable key-value pairs are fetched via 220 | * SPARQL queries and sent to the Lucene indexer. 221 | * 222 | * @param dataPath the path of the data to load 223 | * @param tdbPath the path of the TDB2 on-disk structure 224 | * @param cleanIndex indicates whether to clean the Lucene index before indexing 225 | * @param xmlConfig the configuration file used for indexing 226 | */ 227 | private void buildDisk(IndexConfig config) { 228 | 229 | // Connect to TDB2 graph on disk 230 | DatasetGraph datasetGraph = DatabaseMgr.connectDatasetGraph(config.getTdbPath()); 231 | 232 | // Clear the graph on disk 233 | datasetGraph.begin(ReadWrite.WRITE); 234 | datasetGraph.clear(); 235 | datasetGraph.commit(); 236 | datasetGraph.end(); 237 | 238 | logger.info("Fetching files..."); 239 | 240 | // Fetch the files to load 241 | File[] filesToLoad = getFilesToLoad(config); 242 | 243 | if (filesToLoad == null || filesToLoad.length == 0) { 244 | logger.info("Nothing to load. Exiting."); 245 | return; 246 | } 247 | 248 | logger.info("Creating bulk loader..."); 249 | 250 | // Create a parallel loader 251 | DataLoader loader = LoaderFactory.parallelLoader(datasetGraph, new MonitorOutput() { 252 | @Override 253 | public void print(String fmt, Object... args) { 254 | logger.info(String.format(fmt, args)); 255 | } 256 | }); 257 | 258 | logger.info("====================================================================="); 259 | logger.info("Loading data at " + config.getDataPath()); 260 | logger.info("====================================================================="); 261 | 262 | // Load with the parallel bulk loader to the TDB2 structure on disk 263 | for (File file : filesToLoad) { 264 | loader.startBulk(); 265 | try { 266 | logger.info("Loading file " + file.getPath() + "..."); 267 | loader.load(file.getPath()); 268 | loader.finishBulk(); 269 | } catch (RuntimeException ex) { 270 | ex.printStackTrace(); 271 | loader.finishException(ex); 272 | throw ex; 273 | } 274 | } 275 | 276 | // Do the indexing 277 | indexData(DatasetFactory.wrap(datasetGraph), config); 278 | } 279 | 280 | /** 281 | * Creates the index by using an existing TDB2 data set on disk. 282 | * The indexable key-value pairs are fetched via SPARQL queries 283 | * and sent to the Lucene indexer. 284 | * 285 | * @param tdbPath the path of the TDB2 helper structure 286 | * @param cleanIndex indicates whether to clean the Lucene index before indexing 287 | * @param xmlConfig the configuration file used for indexing 288 | */ 289 | private void indexDisk(IndexConfig config) { 290 | 291 | logger.info("Connecting to TDB2 data set graph..."); 292 | 293 | // Connect to TDB2 graph on disk 294 | DatasetGraph datasetGraph = DatabaseMgr.connectDatasetGraph(config.getTdbPath()); 295 | 296 | // Do the indexing 297 | indexData(DatasetFactory.wrap(datasetGraph), config); 298 | } 299 | 300 | /** 301 | * indexConfig 302 | * Used by all dataset based indexing methods. Runs the configured queries 303 | * against the the loaded 304 | * Datasets and passes the resulting key-value results to the lookup indexer 305 | * 306 | * @param dataset 307 | * @param lookupIndexer 308 | * @param indexConfig 309 | */ 310 | private void indexData(Dataset dataset, IndexConfig config) { 311 | 312 | try (RDFConnection conn = RDFConnectionFactory.connect(dataset)) { 313 | 314 | for (IndexField indexFieldConfig : config.getIndexFields()) { 315 | 316 | logger.info("====================================================================="); 317 | logger.info("Indexing path for field '" + indexFieldConfig.getFieldName() + "'"); 318 | logger.info("====================================================================="); 319 | 320 | Txn.executeRead(conn, () -> { 321 | Query query = QueryFactory.create(indexFieldConfig.getQuery()); 322 | ResultSet result = conn.query(query).execSelect(); 323 | 324 | logger.info("Iterator created. Indexing..."); 325 | 326 | long time = System.currentTimeMillis(); 327 | indexWriter.indexResult(result, indexFieldConfig); 328 | long elapsed = System.currentTimeMillis() - time; 329 | 330 | logger.info("Path indexed in " + String.format("%d min, %d sec", 331 | TimeUnit.MILLISECONDS.toMinutes(elapsed), 332 | TimeUnit.MILLISECONDS.toSeconds(elapsed) - 333 | TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(elapsed)))); 334 | }); 335 | 336 | dataset.close(); 337 | } 338 | } 339 | } 340 | 341 | private File[] getFilesToLoad(IndexConfig config) { 342 | 343 | File[] filesToLoad = new File[0]; 344 | 345 | if(config.getCollectionUri() != null) { 346 | logger.info("====================================================================="); 347 | logger.info("Fetching Databus Collection Files"); 348 | logger.info("====================================================================="); 349 | 350 | filesToLoad = DatabusUtils.loadDatabusFiles(config.getCollectionUri(), logger); 351 | } 352 | else { 353 | 354 | logger.info("====================================================================="); 355 | logger.info("Fetching files from folder: " + config.getDataPath()); 356 | logger.info("====================================================================="); 357 | 358 | String dataPath = config.getDataPath(); 359 | File dataFile = new File(dataPath); 360 | 361 | if (dataFile.isDirectory()) { 362 | filesToLoad = new File(dataPath).listFiles(new RDFFileFilter()); 363 | } else { 364 | boolean accept = false; 365 | String fileName = dataFile.getName(); 366 | accept |= fileName.contains(".ttl"); 367 | accept |= fileName.contains(".turtle"); 368 | accept |= fileName.contains(".n3"); 369 | accept |= fileName.contains(".nt"); 370 | 371 | if (accept) { 372 | filesToLoad = new File[] { dataFile }; 373 | } 374 | } 375 | } 376 | 377 | return filesToLoad; 378 | } 379 | 380 | 381 | 382 | } 383 | -------------------------------------------------------------------------------- /lookup/src/main/java/org/dbpedia/lookup/searcher/LookupSearcher.java: -------------------------------------------------------------------------------- 1 | package org.dbpedia.lookup.searcher; 2 | 3 | import java.io.File; 4 | import java.io.IOException; 5 | import java.util.ArrayList; 6 | import java.util.Comparator; 7 | import java.util.HashMap; 8 | import java.util.Hashtable; 9 | import java.util.List; 10 | import java.util.Map.Entry; 11 | 12 | import org.apache.lucene.analysis.Analyzer; 13 | import org.apache.lucene.analysis.TokenStream; 14 | import org.apache.lucene.analysis.standard.StandardAnalyzer; 15 | import org.apache.lucene.analysis.tokenattributes.CharTermAttribute; 16 | import org.apache.lucene.document.Document; 17 | import org.apache.lucene.document.LongPoint; 18 | import org.apache.lucene.document.StoredField; 19 | import org.apache.lucene.expressions.Expression; 20 | import org.apache.lucene.expressions.SimpleBindings; 21 | import org.apache.lucene.expressions.js.JavascriptCompiler; 22 | import org.apache.lucene.index.DirectoryReader; 23 | import org.apache.lucene.index.IndexableField; 24 | import org.apache.lucene.index.StoredFields; 25 | import org.apache.lucene.index.Term; 26 | import org.apache.lucene.queries.function.FunctionScoreQuery; 27 | import org.apache.lucene.search.BooleanQuery; 28 | import org.apache.lucene.search.BoostQuery; 29 | import org.apache.lucene.search.DoubleValuesSource; 30 | import org.apache.lucene.search.FuzzyQuery; 31 | import org.apache.lucene.search.IndexSearcher; 32 | import org.apache.lucene.search.PrefixQuery; 33 | import org.apache.lucene.search.Query; 34 | import org.apache.lucene.search.ScoreDoc; 35 | import org.apache.lucene.search.TermQuery; 36 | import org.apache.lucene.search.TopDocs; 37 | import org.apache.lucene.search.highlight.Fragmenter; 38 | import org.apache.lucene.search.highlight.Highlighter; 39 | import org.apache.lucene.search.highlight.InvalidTokenOffsetsException; 40 | import org.apache.lucene.search.highlight.QueryScorer; 41 | import org.apache.lucene.search.highlight.SimpleHTMLFormatter; 42 | import org.apache.lucene.search.highlight.SimpleSpanFragmenter; 43 | import org.apache.lucene.search.BooleanClause.Occur; 44 | import org.apache.lucene.search.join.JoinUtil; 45 | import org.apache.lucene.search.join.ScoreMode; 46 | import org.apache.lucene.store.FSDirectory; 47 | import org.dbpedia.lookup.Constants; 48 | import org.dbpedia.lookup.config.LookupConfig; 49 | import org.dbpedia.lookup.config.LookupField; 50 | import org.dbpedia.lookup.config.QuerySettings; 51 | import org.json.JSONArray; 52 | import org.json.JSONObject;; 53 | 54 | /** 55 | * Constructs queries and runs searches on the lucene index 56 | * 57 | * @author Jan Forberg 58 | * 59 | */ 60 | public class LookupSearcher { 61 | 62 | private static final String FIELD_DOCUMENTS = "docs"; 63 | 64 | private static final String FIELD_RESULT = "result"; 65 | 66 | private static final String FIELD_DOCUMENT_ID = "id"; 67 | 68 | private static final String FIELD_COUNT = "count"; 69 | 70 | private static final String FIELD_VALUE = "value"; 71 | 72 | private static final String FIELD_HIGHLIGHT = "highlight"; 73 | 74 | private IndexSearcher searcher; 75 | 76 | private DoubleValuesSource boostValueSource; 77 | 78 | private SimpleHTMLFormatter formatter; 79 | 80 | private DirectoryReader reader; 81 | 82 | private StandardAnalyzer analyzer; 83 | 84 | private LookupConfig config; 85 | 86 | private FSDirectory directory; 87 | 88 | /** 89 | * Creates a new lookup searcher 90 | * 91 | * @param filePath The file path of the index 92 | * @throws IOException 93 | * @throws java.text.ParseException 94 | */ 95 | public LookupSearcher(LookupConfig config) 96 | throws IOException, java.text.ParseException { 97 | 98 | this.config = config; 99 | 100 | this.formatter = new SimpleHTMLFormatter(); 101 | this.analyzer = new StandardAnalyzer(); 102 | 103 | refresh(); 104 | 105 | createBoostSource(config); 106 | } 107 | 108 | public void refresh() { 109 | 110 | if(directory != null) { 111 | try { 112 | directory.close(); 113 | } catch (IOException e) { 114 | e.printStackTrace(); 115 | } 116 | } 117 | 118 | if(reader != null) { 119 | try { 120 | reader.close(); 121 | } catch (IOException e) { 122 | e.printStackTrace(); 123 | } 124 | } 125 | 126 | try { 127 | this.directory = FSDirectory.open(new File(config.getIndexPath()).toPath()); 128 | this.reader = DirectoryReader.open(directory); 129 | this.searcher = new IndexSearcher(reader); 130 | System.out.println("Searcher has been refreshed"); 131 | } catch (IOException e) { 132 | System.out.println("Searcher could not find an index to read at " + config.getIndexPath() + "."); 133 | } 134 | 135 | } 136 | 137 | private void createBoostSource(LookupConfig config) { 138 | 139 | String boostFormula = config.getBoostFormula(); 140 | 141 | if (boostFormula == null) { 142 | return; 143 | } 144 | 145 | try { 146 | Expression expression = JavascriptCompiler.compile(boostFormula); 147 | SimpleBindings bindings = new SimpleBindings(); 148 | 149 | for (String variable : expression.variables) { 150 | System.out.println("Adding double value source for " + variable); 151 | bindings.add(variable, DoubleValuesSource.fromLongField(variable)); 152 | } 153 | 154 | this.boostValueSource = expression.getDoubleValuesSource(bindings); 155 | 156 | } catch (final Exception e) { 157 | System.err.println("Failed to create boost value source:"); 158 | System.err.println(e.getMessage()); 159 | this.boostValueSource = null; 160 | } 161 | } 162 | 163 | /** 164 | * Searches the index based on a given query 165 | * 166 | * @param queryMap Maps a queryfield for a field specific query 167 | * @param maxHits max number of search results 168 | * @return 169 | */ 170 | public JSONObject search(QuerySettings settings, Hashtable queryMap, 171 | String join) { 172 | 173 | LookupField[] fields = new LookupField[queryMap.size()]; 174 | String[] queries = new String[queryMap.size()]; 175 | 176 | int i = 0; 177 | 178 | for (Entry entry : queryMap.entrySet()) { 179 | fields[i] = entry.getKey(); 180 | queries[i] = entry.getValue(); 181 | i++; 182 | } 183 | 184 | return search(fields, queries, settings, join); 185 | } 186 | 187 | /** 188 | * Searches the index based on a given query 189 | * 190 | * @param maxHits The maximum amount of search results 191 | * @return The search results as a string 192 | */ 193 | public JSONObject search(LookupField[] fields, String[] queries, QuerySettings settings, 194 | String join) { 195 | 196 | if(this.searcher == null) { 197 | return null; 198 | } 199 | 200 | try { 201 | if (fields.length != queries.length) { 202 | return null; 203 | } 204 | 205 | StandardAnalyzer analyzer = new StandardAnalyzer(); 206 | 207 | BooleanQuery.Builder queryBuilder = new BooleanQuery.Builder(); 208 | 209 | for (int i = 0; i < fields.length; i++) { 210 | 211 | String field = fields[i].getName(); 212 | String query = queries[i]; 213 | boolean required = fields[i].isRequired(); 214 | boolean allowPartialMatch = fields[i].isAllowPartialMatch(); 215 | boolean isExact = fields[i].isExact(); 216 | 217 | // System.out.println("Searching on " + field + "(" + fields[i].getType() + ")"); 218 | 219 | if(Constants.CONFIG_FIELD_TYPE_NUMERIC.equals(fields[i].getType())) { 220 | 221 | // System.out.println("Field is numeric."); 222 | 223 | if(query.contains(",")) { 224 | 225 | // System.out.println("Might be a range query"); 226 | 227 | String[] conditionStrings = query.split(","); 228 | 229 | if(conditionStrings.length != 2) { 230 | continue; 231 | } 232 | 233 | int lowerBound = parseIntWithFallback(conditionStrings[0], Integer.MIN_VALUE); 234 | int upperBound = parseIntWithFallback(conditionStrings[1], Integer.MAX_VALUE); 235 | 236 | Query rangeQuery = LongPoint.newRangeQuery(field, lowerBound, upperBound); 237 | // System.out.println("Adding range query with range: " + lowerBound + "," + upperBound); 238 | 239 | queryBuilder.add(rangeQuery, Occur.MUST); 240 | } 241 | 242 | continue; 243 | } 244 | 245 | List tokens; 246 | 247 | if (fields[i].tokenize()) { 248 | 249 | if(isExact) { 250 | 251 | tokens = new ArrayList(); 252 | String[] exactTokens = query.split(" "); 253 | 254 | for(int t = 0; t < exactTokens.length; t++) { 255 | tokens.add(exactTokens[t]); 256 | } 257 | } 258 | else { 259 | tokens = analyze(query, analyzer); 260 | } 261 | 262 | } else { 263 | tokens = new ArrayList(); 264 | 265 | if (isExact) { 266 | tokens.add(query); 267 | } else { 268 | tokens.add(query.toLowerCase()); 269 | } 270 | } 271 | 272 | BooleanQuery.Builder tokenQueryBuilder = new BooleanQuery.Builder(); 273 | 274 | for (String token : tokens) { 275 | 276 | Query boostQuery = new BoostQuery(createQueryFromToken(field, fields[i].isExact(), 277 | token, settings), fields[i].getWeight()); 278 | 279 | tokenQueryBuilder = tokenQueryBuilder.add(boostQuery, 280 | allowPartialMatch ? Occur.SHOULD : Occur.MUST); 281 | } 282 | 283 | queryBuilder = queryBuilder.add(tokenQueryBuilder.build(), required ? Occur.MUST : Occur.SHOULD); 284 | } 285 | 286 | analyzer.close(); 287 | 288 | Query query = queryBuilder.build(); 289 | 290 | if (boostValueSource != null) { 291 | query = FunctionScoreQuery.boostByValue(query, boostValueSource); 292 | } 293 | 294 | TopDocs joinDocs = null; 295 | 296 | if (join != null) { 297 | 298 | joinDocs = this.searcher.search(query, 10000); 299 | 300 | 301 | query = JoinUtil.createJoinQuery(FIELD_DOCUMENT_ID, true, join, 302 | query, this.searcher, ScoreMode.None); 303 | 304 | System.out.println(query); 305 | } 306 | 307 | return getReturnResults(fields, settings, query, join, joinDocs); 308 | 309 | } catch (IOException e) { 310 | 311 | System.out.println("querying went wrong"); 312 | e.printStackTrace(); 313 | } 314 | 315 | return null; 316 | } 317 | 318 | private JSONObject getReturnResults(LookupField[] fields, QuerySettings settings, Query query, String join, TopDocs joinDocs) throws IOException { 319 | ArrayList documents = runQuery(query, settings.getMaxResult()); 320 | JSONArray documentArray = new JSONArray(); 321 | HashMap joinScoreMap = null; 322 | 323 | if(join != null) { 324 | joinScoreMap = new HashMap<>(); 325 | StoredFields storedFields = searcher.storedFields(); 326 | ScoreDoc[] hits = joinDocs.scoreDocs; 327 | 328 | for (int i = 0; i < hits.length; i++) { 329 | 330 | int docId = hits[i].doc; 331 | Document document = storedFields.document(docId); 332 | IndexableField field = document.getField(FIELD_DOCUMENT_ID); 333 | 334 | if(field == null) { 335 | continue; 336 | } 337 | 338 | // System.out.println("Adding to score map: " + field.stringValue() + ", score: " + hits[i].score); 339 | joinScoreMap.put(field.stringValue(), hits[i].score); 340 | } 341 | } 342 | 343 | for (ScoredDocument document : documents) { 344 | 345 | if(join != null) { 346 | 347 | float score = 0; 348 | IndexableField[] joinFields = document.getDocument().getFields(join); 349 | 350 | for(IndexableField joinField : joinFields) { 351 | String value = joinField.stringValue(); 352 | 353 | if(joinScoreMap.containsKey(value)) { 354 | score += joinScoreMap.get(value); 355 | } 356 | } 357 | 358 | // System.out.println("Set joined score to " + score); 359 | document.setScore(score); 360 | } 361 | } 362 | 363 | documents.sort(new ScoreDocumentComparator()); 364 | 365 | for (ScoredDocument document : documents) { 366 | 367 | if (document.getScore() < settings.getMinScore()) { 368 | continue; 369 | } 370 | 371 | ArrayList scoreList = new ArrayList(); 372 | scoreList.add("" + document.getScore()); 373 | 374 | HashMap> documentMap = parseResult(query, fields, 375 | document.getDocument(), settings.getFormat()); 376 | 377 | documentMap.put("score", scoreList); 378 | documentArray.put(documentMap); 379 | } 380 | 381 | JSONObject returnResults = new JSONObject(); 382 | returnResults.put(settings.getFormat().equalsIgnoreCase(LookupConfig.CONFIG_FIELD_FORMAT_XML) ? FIELD_RESULT 383 | : FIELD_DOCUMENTS, documentArray); 384 | 385 | return returnResults; 386 | } 387 | 388 | /** 389 | * Creates a query for a search term token. The query is composed of a prefix 390 | * query, 391 | * a fuzzy query with the maximum supported edit distance of 2 and an exact 392 | * match query. 393 | * Exact matches are weighted much higher then prefix or fuzzy matches. 394 | * The weights can be adjusted via the config file 395 | * 396 | * @param field 397 | * @param token 398 | * @return 399 | * @throws IOException 400 | */ 401 | private Query createQueryFromToken(String field, boolean isExact, String token, QuerySettings settings) 402 | throws IOException { 403 | 404 | if (isExact) { 405 | return new BoostQuery(new TermQuery(new Term(field, token)), settings.getExactMatchBoost()); 406 | } 407 | 408 | Term term = new Term(field, token); 409 | 410 | Query prefixQuery = new BoostQuery(new PrefixQuery(term), settings.getPrefixMatchBoost()); 411 | Query fuzzyQuery = new BoostQuery( 412 | new FuzzyQuery(term, settings.getFuzzyEditDistance(), settings.getFuzzyPrefixLength()), 413 | settings.getFuzzyMatchBoost()); 414 | Query termQuery = new BoostQuery(new TermQuery(term), settings.getExactMatchBoost()); 415 | 416 | BooleanQuery.Builder builder = new BooleanQuery.Builder(); 417 | builder.setMinimumNumberShouldMatch(1); 418 | 419 | if (settings.getPrefixMatchBoost() > 0) { 420 | builder.add(prefixQuery, Occur.SHOULD); 421 | } 422 | 423 | if (settings.getFuzzyMatchBoost() > 0) { 424 | builder.add(fuzzyQuery, Occur.SHOULD); 425 | } 426 | 427 | if (settings.getExactMatchBoost() > 0) { 428 | builder.add(termQuery, Occur.SHOULD); 429 | } 430 | 431 | return builder.build(); 432 | } 433 | 434 | private List analyze(String text, Analyzer analyzer) throws IOException { 435 | List result = new ArrayList(); 436 | TokenStream tokenStream = analyzer.tokenStream(null, text); 437 | CharTermAttribute attr = tokenStream.addAttribute(CharTermAttribute.class); 438 | tokenStream.reset(); 439 | while (tokenStream.incrementToken()) { 440 | result.add(attr.toString()); 441 | } 442 | tokenStream.close(); 443 | return result; 444 | } 445 | 446 | /** 447 | * Runs a query and returns the results as a list of documents 448 | * 449 | * @param query 450 | * @param maxResults 451 | * @return 452 | * @throws IOException 453 | * @throws InvalidTokenOffsetsException 454 | */ 455 | private ArrayList runQuery(Query query, int maxResults) throws IOException { 456 | 457 | ArrayList resultList = new ArrayList(); 458 | 459 | if (maxResults == 0) { 460 | 461 | int hitCount = searcher.count(query); 462 | 463 | ScoredDocument scoredDocument = new ScoredDocument(); 464 | 465 | Document document = new Document(); 466 | document.add(new StoredField(FIELD_COUNT, "" + hitCount)); 467 | 468 | scoredDocument.setDocument(document); 469 | scoredDocument.setScore(1); 470 | 471 | resultList.add(scoredDocument); 472 | return resultList; 473 | } 474 | 475 | TopDocs docs = searcher.search(query, maxResults); 476 | StoredFields storedFields = searcher.storedFields(); 477 | ScoreDoc[] hits = docs.scoreDocs; 478 | 479 | for (int i = 0; i < hits.length; i++) { 480 | 481 | int docId = hits[i].doc; 482 | // System.out.println(searcher.explain(query, docId)); 483 | 484 | Document document = storedFields.document(docId); 485 | 486 | ScoredDocument scoredDocument = new ScoredDocument(); 487 | scoredDocument.setDocument(document); 488 | scoredDocument.setScore(hits[i].score); 489 | resultList.add(scoredDocument); 490 | } 491 | 492 | return resultList; 493 | } 494 | 495 | /** 496 | * Creates a string-value map from a document and tries to highlight the query 497 | * using the query and search fields used to retrieve the document 498 | * 499 | * @param document The document 500 | * @return The string-value map 501 | * @throws IOException 502 | */ 503 | private HashMap> parseResult(Query query, LookupField[] fields, Document document, 504 | String fieldFormat) { 505 | 506 | HashMap> documentMap = new HashMap>(); 507 | 508 | for (IndexableField f : document.getFields()) { 509 | 510 | if (!documentMap.containsKey(f.name())) { 511 | documentMap.put(f.name(), new ArrayList()); 512 | } 513 | 514 | String value = f.stringValue(); 515 | String name = f.name(); 516 | 517 | JSONObject jsonValue = new JSONObject(); 518 | jsonValue.put(FIELD_VALUE, value); 519 | 520 | // Highlight the document field, if the field is one of the search fields 521 | for (LookupField field : fields) { 522 | 523 | if (name.equals(field.getName()) && field.isHighlight()) { 524 | 525 | String highlightValue = highlightField(query, name, value); 526 | 527 | if (highlightValue != null && fieldFormat.equalsIgnoreCase(LookupConfig.CONFIG_FIELD_FORMAT_JSON)) { 528 | value = highlightValue; 529 | } 530 | 531 | if (fieldFormat.equalsIgnoreCase(LookupConfig.CONFIG_FIELD_FORMAT_JSON_FULL)) { 532 | jsonValue.put(FIELD_HIGHLIGHT, highlightValue != null ? highlightValue : value); 533 | } 534 | 535 | break; 536 | } 537 | } 538 | 539 | if (fieldFormat.equalsIgnoreCase(LookupConfig.CONFIG_FIELD_FORMAT_JSON_FULL)) { 540 | documentMap.get(f.name()).add(jsonValue); 541 | } else { 542 | documentMap.get(f.name()).add(value); 543 | } 544 | } 545 | 546 | return documentMap; 547 | } 548 | 549 | private String highlightField(Query query, String name, String value) { 550 | 551 | QueryScorer scorer = new QueryScorer(query, name); 552 | 553 | // used to markup highlighted terms found in the best sections of a text 554 | Highlighter highlighter = new Highlighter(formatter, scorer); 555 | 556 | // It breaks text up into same-size texts but does not split up spans 557 | Fragmenter fragmenter = new SimpleSpanFragmenter(scorer); 558 | 559 | highlighter.setTextFragmenter(fragmenter); 560 | 561 | try { 562 | return highlighter.getBestFragment(analyzer, name, value); 563 | } catch (IOException e) { 564 | System.out.println("hightlighting went wrong"); 565 | return value; 566 | } catch (InvalidTokenOffsetsException e) { 567 | System.out.println("hightlighting went wrong"); 568 | return value; 569 | } catch (IllegalArgumentException e) { 570 | System.err.println("hightlighting went wrong"); 571 | System.err.println(e); 572 | return value; 573 | } 574 | } 575 | 576 | public void close() { 577 | try { 578 | reader.close(); 579 | } catch (IOException e) { 580 | e.printStackTrace(); 581 | } 582 | } 583 | 584 | private int parseIntWithFallback(String val, int defaultValue) { 585 | int result; 586 | try { 587 | result = Integer.parseInt(val); 588 | } catch(NumberFormatException ex) { 589 | result = defaultValue; 590 | } 591 | 592 | return result; 593 | } 594 | 595 | public static class ScoredDocument { 596 | private Document document; 597 | 598 | private float score; 599 | 600 | public Document getDocument() { 601 | return document; 602 | } 603 | 604 | public void setDocument(Document document) { 605 | this.document = document; 606 | } 607 | 608 | public float getScore() { 609 | return score; 610 | } 611 | 612 | public void setScore(float score) { 613 | this.score = score; 614 | } 615 | } 616 | 617 | public class ScoreDocumentComparator implements Comparator { 618 | @Override 619 | public int compare(ScoredDocument doc1, ScoredDocument doc2) { 620 | // Compare scores in descending order 621 | return Float.compare(doc2.getScore(), doc1.getScore()); 622 | } 623 | } 624 | } 625 | --------------------------------------------------------------------------------