List of usage examples for org.apache.lucene.search.spell SpellChecker SpellChecker
public SpellChecker(Directory spellIndex) throws IOException
From source file:com.mhs.qsol.SuggestedSearch.java
License:Apache License
private String getTerm(String term) { if (term.length() == 0) { return ""; }/*from ww w . j av a 2 s . com*/ TokenStream source = analyzer.tokenStream("", new StringReader(term)); CharTermAttribute charTermAtrib = source.getAttribute(CharTermAttribute.class); String anaTerm = null; try { source.incrementToken(); anaTerm = charTermAtrib.toString(); if (source.incrementToken()) { return term; } } catch (IOException e2) { throw new RuntimeException(e2); } if (spellChecker == null) { try { spellChecker = new SpellChecker(didYouMeanDirectory); } catch (IOException e1) { throw new RuntimeException(e1); } } String returnTerm = null; try { if (spellChecker.exist(term)) { return term; } spellChecker.setAccuracy(.000f); String[] similarWords = spellChecker.suggestSimilar(anaTerm, 1); if (similarWords.length == 0) { return term; } // suggestedQuery = true; returnTerm = similarWords[0]; } catch (IOException e) { throw new RuntimeException(e); } foundSuggestion = true; return returnTerm; }
From source file:com.stratelia.webactiv.applicationIndexer.control.TestApplicationDYMIndexer.java
License:Open Source License
/** * check the existence of the given word in the index * * @param indexPath index path's//from w w w .j ava 2 s . co m * @param word String to check * @return * @throws IOException */ private boolean checkExistingWord(String indexPath, String word) throws IOException { File file = new File(indexPath); FSDirectory directory = FSDirectory.open(file); SpellChecker spellChecker = new SpellChecker(directory); return spellChecker.exist(word); }
From source file:edu.sdsc.scigraph.vocabulary.VocabularyNeo4jImpl.java
License:Apache License
@Inject public VocabularyNeo4jImpl(GraphDatabaseService graph, @Nullable @IndicatesNeo4jGraphLocation String neo4jLocation, CurieUtil curieUtil, NodeTransformer transformer) throws IOException { this.graph = graph; this.curieUtil = curieUtil; this.transformer = transformer; if (null != neo4jLocation) { Directory indexDirectory = FSDirectory .open(new File(new File(neo4jLocation), "index/lucene/node/node_auto_index")); Directory spellDirectory = FSDirectory .open(new File(new File(neo4jLocation), "index/lucene/spellchecker")); spellChecker = new SpellChecker(spellDirectory); try (IndexReader reader = IndexReader.open(indexDirectory)) { IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_36, new KeywordAnalyzer()); spellChecker.indexDictionary( new LuceneDictionary(reader, NodeProperties.LABEL + LuceneUtils.EXACT_SUFFIX), config, true);/*from w w w . j a va 2s . co m*/ } } else { spellChecker = null; } }
From source file:engine.easy.search.EasySearchEngine.java
License:Apache License
private SpellChecker getSpecSpellChecker() { SpellChecker spellchecker = null;//from w ww .j ava 2 s . c om try { File dir = new File(AppConstants.DICTIONARY_INDEX_PATH); Directory directory = FSDirectory.open(dir); spellchecker = new SpellChecker(new RAMDirectory()); spellchecker.indexDictionary(new PlainTextDictionary(new File(AppConstants.DICTIONARY_PATH))); } catch (Exception e) { System.out.println("Exception: getSpecSpellChecker" + e.toString()); } return spellchecker; }
From source file:engine.easy.util.SuggestionSpellService.java
License:Apache License
public static void main(String[] args) throws Exception { File dir = new File(AppConstants.DICTIONARY_INDEX_PATH); Directory directory = FSDirectory.open(dir); SpellChecker spellChecker = new SpellChecker(new RAMDirectory()); spellChecker.indexDictionary(new PlainTextDictionary(new File(AppConstants.DICTIONARY_PATH))); String wordForSuggestions = "hee"; int suggestionsNumber = 3; String[] suggestions = spellChecker.suggestSimilar(wordForSuggestions, suggestionsNumber); if (suggestions != null && suggestions.length > 0) { for (String word : suggestions) { System.out.println("Did you mean:" + word); }//w w w.j a v a2 s .c om } else { System.out.println("No suggestions found for word:" + wordForSuggestions); } }
From source file:es.pode.indexador.negocio.servicios.busqueda.SrvBuscadorServiceImpl.java
License:Open Source License
/** * @see es.pode.indexador.negocio.servicios.busqueda.SrvBuscadorService#busquedaSimple(es.pode.indexador.negocio.servicios.busqueda.ParamSimpleVO) * @param ParamSimpleVO Este VO alberga los parametros aceptados en la busqueda simple. * @return DocumentosVO Esta clase representa los resultados de una busqueda. */// ww w . j a v a 2s .c om protected es.pode.indexador.negocio.servicios.busqueda.DocumentosVO handleBusquedaSimple( es.pode.indexador.negocio.servicios.busqueda.ParamSimpleVO paramBusq) throws java.lang.Exception { DocumentosVO respuesta = new DocumentosVO(); if (logger.isDebugEnabled()) logger.debug("Los par metros son idiomaBusqueda[" + paramBusq.getIdiomaBusqueda() + "] idiomaNavegacion [" + paramBusq.getIdiomaNavegacion() + "] palabarasclave [" + paramBusq.getPalabrasClave() + "]"); DisjunctionMaxQuery query = new DisjunctionMaxQuery(0.01f); Hits hits = this.internaBusquedaSimple(paramBusq, query); if (logger.isDebugEnabled()) logger.debug("Se devuelven los hits"); if (hits != null && hits.length() == 0) { if (logger.isDebugEnabled()) logger.debug("Se devuelven los hits NULL o 0 vamos a por las sugerencias"); Directory directorioIndiceSpell = this.indiceSpell(paramBusq.getIdiomaBusqueda()); if (logger.isDebugEnabled()) logger.debug("El indice de spellchecker es " + directorioIndiceSpell); SpellChecker spellChecker = new SpellChecker(directorioIndiceSpell); String sQuery = query.toString(); if (!spellChecker.exist(sQuery) && (paramBusq.getPalabrasClave() != null && !paramBusq.getPalabrasClave().equals(""))) { String[] sugerencias = spellChecker.suggestSimilar(paramBusq.getPalabrasClave().toLowerCase(), 10); respuesta.setSugerencias(sugerencias); } else respuesta.setSugerencias(new String[] {}); } else { respuesta.setResultados(this.getArrayDocsFromHits(hits, (hits.length() > paramBusq.getNumeroResultados().intValue()) ? paramBusq.getNumeroResultados().intValue() : hits.length())); } return respuesta; }
From source file:es.pode.indexador.negocio.servicios.busqueda.SrvBuscadorServiceImpl.java
License:Open Source License
/** * @see es.pode.indexador.negocio.servicios.busqueda.SrvBuscadorService#busquedaAvanzada(es.pode.indexador.negocio.servicios.busqueda.ParamAvanzadoVO) * @param ParamAvanzadoVO VO que alberga los parametros que acepta una busqueda avanzada. * @return DocumentosVO Esta clase representa los resultados de una busqueda. *//*from w w w . j a v a2 s . c om*/ protected es.pode.indexador.negocio.servicios.busqueda.DocumentosVO handleBusquedaAvanzada( es.pode.indexador.negocio.servicios.busqueda.ParamAvanzadoVO paramBusq) throws java.lang.Exception { // Implementamos la busqueda avanzada. DocumentosVO respuesta = new DocumentosVO(); if (logger.isDebugEnabled()) logger.debug("SrvBuscadorServiceImpl - handleBusquedaAvanzada: Parametros de la busqueda avanzada " + paramBusqAvanz2String(paramBusq)); DisjunctionMaxQuery query = new DisjunctionMaxQuery(0.01f); long start = System.currentTimeMillis(); Object[] hits = null; boolean resultadoUnico = false; // Some fixing with "*" and ".*" if (paramBusq.getPalabrasClave() != null && !paramBusq.getPalabrasClave().trim().equals("*") && !paramBusq.getPalabrasClave().trim().equals(".*")) { if (paramBusq.getPalabrasClave().trim().toLowerCase() .startsWith(props.getProperty("agrega_admin") + " ")) { hits = new Hits[1]; hits = this.internaBusquedaQuery(paramBusq, paramBusq.getPalabrasClave().toLowerCase().trim() .substring((props.getProperty("agrega_admin") + " ").length()), query, false, null); } else if (paramBusq.getPalabrasClave().trim().toLowerCase() .startsWith(props.getProperty("agrega_todos") + " ")) { IndiceVO[] idiomas = this.handleObtenerIdiomasBusqueda(); hits = new Hits[idiomas.length]; hits = this.internaBusquedaQuery(paramBusq, paramBusq.getPalabrasClave().toLowerCase().trim() .substring((props.getProperty("agrega_todos") + " ").length()), query, true, idiomas); } else { resultadoUnico = true; hits = new Hits[1]; hits[0] = internaBusquedaAvanzada(paramBusq, query); } } else { resultadoUnico = true; hits = new Hits[1]; hits[0] = internaBusquedaAvanzada(paramBusq, query); } long end = System.currentTimeMillis(); logger.debug("SrvBuscadorServiceImpl - handleBusquedaAvanzada : Busqueda local realizada en =" + (end - start) + " milisegundos."); if (logger.isDebugEnabled()) { logger.debug("Se devuelven los hits"); logger.debug("Se devuelven los hits NULL o 0 vamos a por las sugerencias"); } if (paramBusq.getBusquedaSimpleAvanzada() != null && !paramBusq.getBusquedaSimpleAvanzada().equals(BUSCARRSS)) { try { Directory directorioIndiceSpell = this.indiceSpell(paramBusq.getIdiomaBusqueda()); if (logger.isDebugEnabled()) logger.debug("El indice de spellchecker es " + directorioIndiceSpell); SpellChecker spellChecker = new SpellChecker(directorioIndiceSpell); String sQuery = query.toString(); // TODO: retocar las sugerencias para que tengan en cuenta algo mas que los parametros de "keywords"? if (!spellChecker.exist(sQuery) && (paramBusq.getPalabrasClave() != null && !paramBusq.getPalabrasClave().equals(""))) { List claveBusqueda = this.obtenerPalabrasClave(paramBusq.getPalabrasClave().toLowerCase(), false); List<String> sugerencias = new ArrayList<String>(); if (claveBusqueda != null && claveBusqueda.size() > 0) { boolean suficientes = false; for (int i = 0; i < claveBusqueda.size() && !suficientes; i++) { if (!((String) claveBusqueda.get(i)).equals("")) { String[] suge = spellChecker.suggestSimilar((String) claveBusqueda.get(i), NUMERO_SUGERENCIAS); if (suge != null && suge.length > 0) { for (int k = 0; k < suge.length && sugerencias.size() < NUMERO_SUGERENCIAS; k++) { boolean encontrado = false; for (int j = 0; j < sugerencias.size() && !encontrado; j++) { if (sugerencias.get(j).toString().equals(suge[k])) encontrado = true; } if (!encontrado && validarPersonalizada(paramBusq)) { Hits hitSugerencias = null; ParamAvanzadoVO paramBusqSug = paramBusq; paramBusqSug.setPalabrasClave(suge[k]); try { hitSugerencias = internaBusquedaAvanzada(paramBusqSug, query); if (hitSugerencias != null && hitSugerencias.length() > 0) sugerencias.add(suge[k]); } catch (Exception e) { logger.error( "SrvBuscadorServiceImpl - handleBuscarAvanzado:Error solicitando comprobaci n sugerencia avanzada. Sugerencia=" + suge[k], e); } } else if (!encontrado && !validarPersonalizada(paramBusq)) sugerencias.add(suge[k]); } } if (sugerencias.size() == NUMERO_SUGERENCIAS) suficientes = true; } } } String[] cargarSugerencias = new String[] {}; if (sugerencias != null && sugerencias.size() > 0) { cargarSugerencias = new String[sugerencias.size()]; for (int i = 0; i < sugerencias.size(); i++) { cargarSugerencias[i] = sugerencias.get(i); } } respuesta.setSugerencias(cargarSugerencias); } else respuesta.setSugerencias(new String[] {}); } catch (Exception e) { logger.error( "SrvBuscadorServiceImpl - handleBuscarAvanzado:Error solicitando sugerencias para idioma:" + paramBusq.getIdiomaBusqueda(), e); respuesta.setSugerencias(new String[] {}); } try { es.pode.indexador.negocio.servicios.busqueda.TaxonVO[] cargarTesauros = new es.pode.indexador.negocio.servicios.busqueda.TaxonVO[] {}; if (paramBusq.getPalabrasClave() != null && !paramBusq.getPalabrasClave().trim().equals("")) { List palabrasTesauro = this.obtenerPalabrasClave(paramBusq.getPalabrasClave().toLowerCase(), true); List<String> nombreTesauros = new ArrayList<String>(); List<String> identificadorTesauros = new ArrayList<String>(); if (palabrasTesauro != null && palabrasTesauro.size() > 0) { int numeroTax = 0; for (int i = 0; i < palabrasTesauro.size() && (numeroTax < Integer.parseInt(props.getProperty("numero_tesauros"))); i++) { TaxonVO[] taxones = this.getSrvTesaurosServices().obtenerTerminosRelacionadosPorTexto( (String) palabrasTesauro.get(i), props.getProperty("nombre_tesauro"), paramBusq.getIdiomaBusqueda()); String[] idTesauro = new String[taxones.length]; for (int k = 0; k < taxones.length; k++) { idTesauro[k] = taxones[k].getId(); } for (int k = 0; k < taxones.length && (numeroTax < Integer.parseInt(props.getProperty("numero_tesauros"))); k++) { Integer[] tesauros = NumTermsArbol .obtenerNumeroNodos(idTesauro, getIndexPathByLanguage(paramBusq.getIdiomaBusqueda()), "tesauro") .getConteo(); if (idTesauro != null && idTesauro.length != 0) { for (int j = 0; j < idTesauro.length; j++) { if (idTesauro[j].equals(taxones[k].getId())) { if (tesauros[j].intValue() > 0) { nombreTesauros.add(taxones[k].getValorTax()); identificadorTesauros.add(taxones[k].getId()); numeroTax = numeroTax + 1; } } } } } } } if (nombreTesauros != null && nombreTesauros.size() > 0) { cargarTesauros = new es.pode.indexador.negocio.servicios.busqueda.TaxonVO[nombreTesauros .size()]; for (int i = 0; i < nombreTesauros.size(); i++) { cargarTesauros[i] = new es.pode.indexador.negocio.servicios.busqueda.TaxonVO( identificadorTesauros.get(i).toString(), nombreTesauros.get(i).toString()); } } respuesta.setTesauros(cargarTesauros); } else respuesta.setTesauros(new es.pode.indexador.negocio.servicios.busqueda.TaxonVO[] {}); } catch (Exception e) { logger.error( "SrvBuscadorServiceImpl - handleBuscarAvanzado:Error obteniendo sugerencias de tesauro [" + props.getProperty("nombre_tesauro") + "] con:" + paramBusq.getPalabrasClave() + " n mero de tesauros m ximo solicitado=" + props.getProperty("numero_tesauros") + " e idioma=" + paramBusq.getIdiomaBusqueda(), e); respuesta.setTesauros(new es.pode.indexador.negocio.servicios.busqueda.TaxonVO[] {}); } } if (hits == null || (resultadoUnico && hits[0] == null)) { respuesta.setTotalResultados(new Integer(0)); respuesta.setNumeroResultados(new Integer(0)); respuesta.setNumDocumentosIndice(new Integer(0)); } else { long start2 = System.currentTimeMillis(); if (hits.length > 1) { int totalResultados = 0; List docsList = new ArrayList(); for (int i = 0; i < hits.length && docsList.size() <= paramBusq.getNumeroResultados().intValue(); i++) { if (hits[i] != null && ((Hits) hits[i]).length() > 0) { totalResultados = totalResultados + ((Hits) hits[i]).length(); DocVO[] docs = this.getArrayDocsFromHits((Hits) hits[i], ((((Hits) hits[i]).length() < paramBusq.getNumeroResultados().intValue()) || paramBusq.getNumeroResultados().intValue() == -1) ? ((Hits) hits[i]).length() : paramBusq.getNumeroResultados().intValue()); for (int j = 0; j < docs.length; j++) { docsList.add(docs[j]); } } } DocVO[] docs = new DocVO[docsList.size()]; for (int i = 0; i < docs.length; i++) { docs[i] = (DocVO) docsList.get(i); } respuesta.setTotalResultados(new Integer(totalResultados)); respuesta.setResultados(docs); } else { respuesta.setTotalResultados(new Integer(((Hits) hits[0]).length())); respuesta.setResultados(this.getArrayDocsFromHits((Hits) hits[0], ((((Hits) hits[0]).length() < paramBusq.getNumeroResultados().intValue()) || paramBusq.getNumeroResultados().intValue() == -1) ? ((Hits) hits[0]).length() : paramBusq.getNumeroResultados().intValue())); } end = System.currentTimeMillis(); logger.debug("SrvBuscadorServiceImpl - handleBusquedaAvanzada : Mapeo local realizado en =" + (end - start2) + " milisegundos."); IndexReader reader = IndexReader.open(this.getIndexByLanguage(paramBusq.getIdiomaBusqueda())); respuesta.setNumDocumentosIndice(new Integer(reader.numDocs())); respuesta.setNumeroResultados(new Integer(respuesta.getResultados().length)); } logger.debug("SrvBuscadorServiceImpl - handleBusquedaAvanzada : Busqueda local realizada en =" + (end - start) + " milisegundos."); return respuesta; }
From source file:es.pode.indexador.negocio.servicios.indexado.SrvIndexadorServiceImpl.java
License:Open Source License
/** * Generacin del repositorio que nos muestra las palabras sugeridas * @param directorioIndiceSimple Objeto directorio con informacin del directorio del repositorio de ndices * @param directorioIndiceSpell Objeto directorio con la informacin del directorio del repositorio de las palabras sugeridas * @throws IOException/*w ww .j a v a 2s.com*/ * @throws Exception */ private synchronized void spellCheckerAdd(Directory directorioIndiceSimple, Directory directorioIndiceSpell) throws IOException, Exception { if (logger.isDebugEnabled()) logger.debug("Comprobamos el directorio del spellchecker = " + directorioIndiceSpell + " y el normal = " + directorioIndiceSimple); if (IndexReader.indexExists(directorioIndiceSimple)) { if (logger.isDebugEnabled()) logger.debug("El ndiceSimple " + directorioIndiceSimple + "existe y lo abrimos para leer."); IndexReader indexReader = IndexReader.open(directorioIndiceSimple); String field = props.getProperty("campo_titulo"); if (logger.isDebugEnabled()) logger.debug("Creamos un diccionario para el campo = " + field); Dictionary dictionary = new LuceneDictionary(indexReader, field); if (logger.isDebugEnabled()) logger.debug("Creamos el spellchecher[" + directorioIndiceSpell + "]"); SpellChecker spellChecker = new SpellChecker(directorioIndiceSpell); if (logger.isDebugEnabled()) logger.debug("Indexamos el diccionario de [" + directorioIndiceSimple + "] en el spell [" + directorioIndiceSpell + "]"); spellChecker.indexDictionary(dictionary); field = props.getProperty("campo_descripcion"); if (logger.isDebugEnabled()) logger.debug("Creamos un diccionario para el campo = " + field); dictionary = new LuceneDictionary(indexReader, field); spellChecker.indexDictionary(dictionary); indexReader.close(); directorioIndiceSpell.close(); } else { logger.error("No existe el indice en el directorio[" + directorioIndiceSimple + "]"); throw new Exception("No existe el ndice en el directorio = " + directorioIndiceSimple); } }
From source file:es.pode.indexador.negocio.servicios.indexado.SrvIndexadorServiceImpl.java
License:Open Source License
/** * Reinicio del repositorio que nos muestra las palabras sugeridas * @param directorioIndiceSpell Objeto directorio con la informacin del directorio del repositorio de las palabras sugeridas * @throws IOException/* w w w .ja va 2 s . co m*/ * @throws Exception */ private void spellCheckerReset(Directory directorioIndiceSpell) throws IOException, Exception { if (logger.isDebugEnabled()) logger.debug("Comprobamos el directorio del spellchecker [" + directorioIndiceSpell + "]"); if (IndexReader.indexExists(directorioIndiceSpell)) { if (logger.isDebugEnabled()) logger.debug("Creamos el spellchecher [" + directorioIndiceSpell + "]"); SpellChecker spellChecker = new SpellChecker(directorioIndiceSpell); if (logger.isDebugEnabled()) logger.debug("Reseteamos el contenido del spellchecher[" + directorioIndiceSpell + "]"); spellChecker.clearIndex(); directorioIndiceSpell.close(); } // si no existe el no es necesario reiniciarlo // else // { // logger.error("No existe el spellchecher en el directorio["+directorioIndiceSpell+"]"); // throw new Exception("No existe el spellchecher en el directorio = " + directorioIndiceSpell); // } }
From source file:fastcampus.lucene.example.search.SpellCheckerExample.java
License:Apache License
public static void main(String[] args) throws Exception { Directory directory = FSDirectory.open(Paths.get("./index/spell/")); SpellChecker spellChecker = new SpellChecker(directory); //Analyzer analyzer = new StandardAnalyzer(); // ? Analyzer analyzer = new Analyzer() { @Override/*from ww w . j a va2 s. co m*/ protected TokenStreamComponents createComponents(String s) { Reader reader = new StringReader(s); Tokenizer tokenizer = new StandardTokenizer(); tokenizer.setReader(reader); String name = "nfc_cf"; Normalizer2 normalizer = Normalizer2.getInstance(null, name, Normalizer2.Mode.DECOMPOSE); TokenFilter filter = new ICUNormalizer2Filter(tokenizer, normalizer); return new TokenStreamComponents(tokenizer, filter); } }; IndexWriterConfig indexWriterConfig = new IndexWriterConfig(analyzer); //?? Writer? ? ? Path path = Paths.get("./data/spell/dic.txt"); spellChecker.setSpellIndex(directory); spellChecker.clearIndex(); spellChecker.indexDictionary(new PlainTextDictionary(path), indexWriterConfig, true); String wordForSuggestions = "?"; //spellChecker.setStringDistance(new LevensteinDistance()); //#Levenstein spellChecker.setStringDistance(new JaroWinklerDistance()); //Jaro-Winkler int suggestionsNumber = 1; String[] suggestions = spellChecker.suggestSimilar(wordForSuggestions, suggestionsNumber); if (suggestions != null && suggestions.length > 0) { for (String word : suggestions) { System.out.println("Did you mean:" + word); } } else { System.out.println("No suggestions found for word:" + wordForSuggestions); } }