List of usage examples for org.apache.lucene.search.spell SpellChecker exist
public boolean exist(String word) throws IOException
From source file:com.appeligo.lucene.DidYouMeanIndexer.java
License:Apache License
public static void createSpellIndex(String field, Directory originalIndexDirectory, Directory spellIndexDirectory) throws IOException { IndexReader indexReader = null;/* w w w . ja v a2 s . co m*/ try { indexReader = IndexReader.open(originalIndexDirectory); Dictionary dictionary = new LuceneDictionary(indexReader, field); SpellChecker spellChecker = new SpellChecker(spellIndexDirectory); spellChecker.indexDictionary(dictionary); if (log.isDebugEnabled()) { spellChecker = new SpellChecker(spellIndexDirectory); // need to re-open to see it work log.debug("Does 'next' exist in the dictionary? " + spellChecker.exist("next")); StringBuilder sb = new StringBuilder(); for (String s : spellChecker.suggestSimilar("noxt", 5, indexReader, "compositeField", true)) { sb.append(s + ", "); } log.debug("Best suggestions for 'noxt': " + sb); } } finally { if (indexReader != null) { indexReader.close(); } } }
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 ww w. ja v a2s . c om * @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: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. *//*from ww w . j a v a2s. c o m*/ 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. *//* ww w . jav 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:org.silverpeas.core.index.search.model.DidYouMeanSearcher.java
License:Open Source License
/** * @param queryDescription/* www .j a v a 2s. c o m*/ * @return * @throws org.silverpeas.core.index.search.model.ParseException * @throws ParseException */ public String[] suggest(QueryDescription queryDescription) throws org.silverpeas.core.index.search.model.ParseException, IOException { spellCheckers.clear(); String[] suggestions = null; // The variable field is only used to parse the query String and to obtain the words that will // be used for the search final String field = "content"; if (StringUtil.isDefined(queryDescription.getQuery())) { // parses the query string to prepare the search Analyzer analyzer = indexManager.getAnalyzer(queryDescription.getRequestedLanguage()); QueryParser queryParser = new QueryParser(field, analyzer); Query parsedQuery; try { parsedQuery = queryParser.parse(queryDescription.getQuery()); } catch (org.apache.lucene.queryparser.classic.ParseException exception) { try { parsedQuery = queryParser.parse(QueryParser.escape(queryDescription.getQuery())); } catch (org.apache.lucene.queryparser.classic.ParseException pe) { throw new org.silverpeas.core.index.search.model.ParseException("DidYouMeanSearcher", pe); } } // splits the query to realize a separated search with each word this.query = parsedQuery.toString(field); StringTokenizer tokens = new StringTokenizer(query); // gets spelling index paths Set<String> spellIndexPaths = indexSearcher.getIndexPathSet(queryDescription.getWhereToSearch()); try { while (tokens.hasMoreTokens()) { SpellChecker spellCheck = new SpellChecker(FSDirectory.open(uploadIndexDir.toPath())); spellCheckers.add(spellCheck); String token = tokens.nextToken().replaceAll("\"", ""); for (String path : spellIndexPaths) { // create a file object with given path File file = new File(path + "Spell"); if (file.exists()) { // create a spellChecker with the file object FSDirectory directory = FSDirectory.open(file.toPath()); spellCheck.setSpellIndex(directory); // if the word exist in the dictionary, we stop the current treatment and search the // next word because the suggestSimilar method will return the same word than the given word if (spellCheck.exist(token)) { continue; } spellCheck.suggestSimilar(token, 1); } } } } catch (IOException e) { SilverLogger.getLogger(this).error(e.getMessage(), e); } suggestions = buildFinalResult(); } return suggestions; }
From source file:org.silverpeas.search.searchEngine.model.DidYouMeanSearcher.java
License:Open Source License
/** * @param queryDescription// w w w .j a v a2 s. c o m * @return * @throws org.silverpeas.search.searchEngine.model.ParseException * @throws ParseException */ public String[] suggest(QueryDescription queryDescription) throws org.silverpeas.search.searchEngine.model.ParseException, IOException { String[] suggestions = null; // The variable field is only used to parse the query String and to obtain the words that will // be used for the search final String field = "content"; if (StringUtil.isDefined(queryDescription.getQuery())) { // parses the query string to prepare the search Analyzer analyzer = new IndexManager().getAnalyzer(queryDescription.getRequestedLanguage()); QueryParser queryParser = new QueryParser(Version.LUCENE_36, field, analyzer); Query parsedQuery; try { parsedQuery = queryParser.parse(queryDescription.getQuery()); } catch (ParseException exception) { throw new org.silverpeas.search.searchEngine.model.ParseException("DidYouMeanSearcher", exception); } // splits the query to realize a separated search with each word this.query = parsedQuery.toString(field); StringTokenizer tokens = new StringTokenizer(query); // gets spelling index paths WAIndexSearcher waIndexSearcher = new WAIndexSearcher(); Set<String> spellIndexPaths = waIndexSearcher .getIndexPathSet(queryDescription.getSpaceComponentPairSet()); try { while (tokens.hasMoreTokens()) { SpellChecker spellCheck = new SpellChecker(FSDirectory.open(uploadIndexDir)); spellCheckers.add(spellCheck); String token = tokens.nextToken().replaceAll("\"", ""); for (String path : spellIndexPaths) { // create a file object with given path File file = new File(path + "Spell"); if (file.exists()) { // create a spellChecker with the file object FSDirectory directory = FSDirectory.open(file); spellCheck.setSpellIndex(directory); // if the word exist in the dictionary, we stop the current treatment and search the // next word because the suggestSimilar method will return the same word than the given word if (spellCheck.exist(token)) { continue; } spellCheck.suggestSimilar(token, 1); } } } } catch (IOException e) { SilverTrace.error("searchEngine", DidYouMeanIndexer.class.toString(), "root.EX_LOAD_IO_EXCEPTION", e); } suggestions = buildFinalResult(); } return suggestions; }
From source file:org.tinymce.spellchecker.LuceneSpellCheckerServlet.java
License:Open Source License
protected List<String> findMisspelledWords(Iterator<String> checkedWordsIterator, String lang) throws SpellCheckException { List<String> misspelledWordsList = new ArrayList<String>(); SpellChecker checker = (SpellChecker) getChecker(lang); try {//from w w w . j av a 2s . co m while (checkedWordsIterator.hasNext()) { String word = checkedWordsIterator.next(); if (!word.equals("") && !checker.exist(word)) { misspelledWordsList.add(word); } } } catch (IOException e) { logger.log(Level.SEVERE, "Failed to find misspelled words", e); throw new SpellCheckException("Failed to find misspelled words", e); } return misspelledWordsList; }
From source file:prman.model.SpellCheckManager.java
License:Open Source License
public String getBestEnd(String begin, Locale loc) { String toReturn = null;/* w w w . j av a2 s . c om*/ SpellChecker sc = getSpellChecker(loc); try { if (sc == null || sc.exist(begin)) return null; IndexSearcher searcher = new IndexSearcher(sc.getSpellIndex()); int bestLength = begin.length() + 3; toReturn = getBestEnd(searcher, new WildcardQuery(new Term(SpellChecker.F_WORD, begin + "????")), bestLength); if (toReturn == null) { toReturn = getBestEnd(searcher, new WildcardQuery(new Term(SpellChecker.F_WORD, begin + "???")), bestLength); if (toReturn == null) { toReturn = getBestEnd(searcher, new WildcardQuery(new Term(SpellChecker.F_WORD, begin + "?????")), bestLength); if (toReturn == null) { toReturn = getBestEnd(searcher, new PrefixQuery(new Term(SpellChecker.F_WORD, begin)), bestLength); } } } } catch (Throwable _t) { Logger.getLogger(getClass().getName()).log(Level.WARNING, "Spell checker error", _t); toReturn = null; } return toReturn; }
From source file:prman.model.SpellCheckManager.java
License:Open Source License
public boolean isGood(String word, Locale loc) throws IOException { if (shouldIgnore(word, loc)) return true; SpellChecker sp = getSpellChecker(loc); int length = word.length(); if (sp == null || length < MIN_WORD_LENGTH) return true; boolean allUppercase = true; for (int iCnt = 0; iCnt < word.length(); iCnt++) { char charz = word.charAt(iCnt); if (Character.isDigit(charz)) return true; if (allUppercase && !Character.isUpperCase(charz)) allUppercase = false;// ww w . jav a 2 s. c o m } if (allUppercase) return true; return sp.exist(word.toLowerCase(loc)); // try // { // return sp == null || sp.exist(word); // } // catch (IOException _ioe) // { // Logger.getLogger(getClass().getName()).log(Level.WARNING, "Spell checker // error", _ioe); // } // return true; }