[Castore-commits] IndexationRechercheLucene.java 1.18 1.19
Neman OULD SID'AHMED
neman at adullact1.hosting.cri74.org
Jeu 17 Aou 10:03:38 CEST 2006
Update of /cvsroot/castore/castore-core/src/java/fr/emn/castor/recherche/metier/lucene
In directory adullact1:/tmp/cvs-serv2770/src/java/fr/emn/castor/recherche/metier/lucene
Modified Files:
IndexationRechercheLucene.java
Log Message:
changement d'une méthode deprecated par une autre
Index: IndexationRechercheLucene.java
===================================================================
RCS file: /cvsroot/castore/castore-core/src/java/fr/emn/castor/recherche/metier/lucene/IndexationRechercheLucene.java,v
retrieving revision 1.18
retrieving revision 1.19
diff -C2 -d -r1.18 -r1.19
*** IndexationRechercheLucene.java 16 Aug 2006 14:38:18 -0000 1.18
--- IndexationRechercheLucene.java 17 Aug 2006 08:03:36 -0000 1.19
***************
*** 57,60 ****
--- 57,61 ----
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.Term;
+ import org.apache.lucene.index.IndexReader.FieldOption;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
***************
*** 75,288 ****
* @author $Author$
* @version $Revision$
! *
*/
public abstract class IndexationRechercheLucene extends AbstractEngine {
! /**
! * utilisation du common logging.
! */
! private static Log log = LogFactory
! .getLog(IndexationRechercheLucene.class);
! /**
! * Le Writer de lucene.
! */
! protected IndexWriter writer;
! /**
! * @see fr.emn.castor.recherche.metier.IIndexeur#addToIndex(
! * java.lang.String)
! */
! public final String addToIndex(final String idDocument)
! throws IndexationException {
! try {
! this.initWriter(false);
! this.indexSubDir = false;
! this.nbDocIndexes = 0;
! // on indexe le contenu du document ...
! this.indexDoc(idDocument);
! } catch (IOException ioe) {
! log.fatal("Erreur lors de l'initialisation du Writer !", ioe);
! throw new IndexationException(ioe.getMessage(), WRITER_ERROR);
! } finally {
! this.closeWriter();
! }
! return String.valueOf(this.nbDocIndexes);
! }
! /**
! * Methode indexant la notice correspondant a l'id donne en paramatre.
! * @param idDocument l'identifiant de la notice du document
! */
! protected final void indexNotice(final String idDocument)
! throws IndexationException {
! // on recupere la notice associée !
! File notice = new File(Facade
! .getInstance().getPathNotice(idDocument));
! this.docType = NOTICE;
! this.indexFichier(notice, idDocument);
! if (log.isDebugEnabled()) {
! log.debug("Fin d'indexation du document : "
! + Facade.getInstance().getNameDoc(idDocument));
! }
! }
! /**
! * @see fr.emn.castor.recherche.metier.IIndexeur#deleteRefFromIndex(
! * java.lang.String)
! */
! public final void deleteRefFromIndex(final String docId)
! throws IndexationException {
! if (log.isDebugEnabled()) {
! log.debug("Suppression de l'index pour le document " + docId);
! }
! try {
! String indexPath = Constants.CASTOR_INDEX_PATH;
! IndexReader reader = IndexReader.open(indexPath);
! Term term = new Term(RechercheConstants.KEYWORD_ID, docId);
! int deleted = reader.deleteDocuments(term);
! reader.close();
! if (log.isDebugEnabled()) {
! log.debug("Suppression OK , " + deleted
! + " item(s) supprimés.");
! }
! } catch (IOException ioe) {
! if (log.isDebugEnabled()) {
! log.fatal("Erreur lors de la suppression du doc " + docId
! + " de l'index.");
! }
! throw new IndexationException(ioe.getMessage(), IO_EXCEPTION);
! }
! }
! /**
! * Methode d'initialisation du writer.
! *
! * @param createNewIndex
! * indique si on ajoute des documents a l'index existant ou si on
! * en cree un nouveau, ecrasant l'ancien. <br>
! * <b>Attention, si l'index n'existe pas, la création sera
! * activée par défaut. </b> si true, creation d'un nouvel index,
! * et destruction de l'ancien. si false, ajout de documents dans
! * le nouvel index.
! * @throws IOException si une erreur survient
! */
! protected void initWriter(final boolean createNewIndex)
! throws IOException {
! String indexDir = Constants.CASTOR_INDEX_PATH;
! boolean create = createNewIndex;
! // on va verifier avant si il existe ou pas un index.
! if (!IndexReader.indexExists(indexDir)) {
! // si l'index n'existe pas, on force la creation
! create = true;
! }
! this.writer = new IndexWriter(indexDir, new WhitespaceAnalyzer(), create);
! }
! /**
! * Methode permettant de fermer le writer.
! */
! protected void closeWriter() {
! try {
! this.writer.close();
! } catch (IOException ioe) {
! log.fatal("Erreur lors de la fermeture du writer : "
! + ioe.getMessage(), ioe);
! }
! }
! /**
! * Methode d'indexation du contenu du fichier donne.
! *
! * @param fichier le fichier a indexer
! * @param id identifiant du document correspondant au fichier
! * @throws IndexationException Si il y a des erreurs lors de l'indexation.
! */
! protected void indexFichier(final File fichier, final String id)
! throws IndexationException {
! if (log.isDebugEnabled()) {
! log.debug("Indexation du document " + fichier + "...");
! }
! // Document Lucene
! Document doc = new Document();
! if (this.docType == -1) {
! throw new IndexationException(UNKNOWN_TYPE);
! }
! XMLLuceneIndexer xmlIndexer = new XMLLuceneIndexer(this.docType);
! doc = xmlIndexer.getDoc(fichier);
! // les fields specifiques au document
! try {
! // ajout du type de fichier (document/notice)
! Field typeField = new Field(
! RechercheConstants.KEYWORD_TYPE_FICHIER, String
! .valueOf(this.docType), Field.Store.YES,
! Field.Index.UN_TOKENIZED);
! doc.add(typeField);
! // ajout de l'id du document
! Field idField = new Field(
! RechercheConstants.KEYWORD_ID, id, Field.Store.YES,
! Field.Index.UN_TOKENIZED);
! doc.add(idField);
! this.writer.addDocument(doc);
! } catch (IOException ioe) {
! log.fatal(ioe.getMessage(), ioe);
! throw new IndexationException(IO_EXCEPTION);
! }
! // on incremente le nombre de documents indexes.
! this.nbDocIndexes += 1;
! }
! /**
! * Methode renvoyant une liste de resultats formates.
! *
! * @param hits les hits lucene
! * @return une liste de Map.
! * @throws IOException si une erreur survient lors de la lecture du hit.
! */
! private List<HashMap<String, String>> transformerHits(final Hits hits)
! throws IOException {
! List<HashMap<String, String>> resultHits = new ArrayList<HashMap<String, String>>();
! ArrayList<String> ids = new ArrayList<String>();
! for (int i = 0; i < hits.length(); i++) {
! Document doc = hits.doc(i);
! float score = hits.score(i);
! String ident = doc.get(RechercheConstants.KEYWORD_ID);
! HashMap<String, String> element = new HashMap<String, String>();
! String typeFichier = doc
! .get(RechercheConstants.KEYWORD_TYPE_FICHIER);
! if ((Integer.parseInt(typeFichier) == NOTICE)
! && (!ids.contains(ident))) {
! // on a recuperer la notice du doc..
! // on ajoute le score associe
! element.put(RechercheConstants.SEARCH_SCORE, String
! .valueOf(score));
! element.put(RechercheConstants.KEYWORD_ID, ident);
! element.putAll(Facade.getInstance().getNoticeMap(ident));
! } else {
! // on a recupere le document, mais a t'on deja la notice ??
! // si oui, inutile de recuperer la notice...
! if (!ids.contains(ident)) {
! // on va rechercher la notice
! element.put(RechercheConstants.SEARCH_SCORE, String
! .valueOf(score));
! element.put(RechercheConstants.KEYWORD_ID, ident);
! element.putAll(Facade.getInstance().getNoticeMap(ident));
! }
! }
! // ajout de l'element
! if (!element.isEmpty()) {
! resultHits.add(element);
! }
! ids.add(ident);
! }
! return resultHits;
! }
! /**
! * Methode renvoyant la liste des cahmps indexés.
! *
! * @return une liste de String.
! * @throws IOException si une erreur survient lors de la lecture du hit.
! */
!
! public final List<String> getFieldNames() {
String indexDir = Constants.CASTOR_INDEX_PATH;
IndexSearcher searcher;
--- 76,297 ----
* @author $Author$
* @version $Revision$
! *
*/
public abstract class IndexationRechercheLucene extends AbstractEngine {
! /**
! * utilisation du common logging.
! */
! private static Log log = LogFactory.getLog(IndexationRechercheLucene.class);
! /**
! * Le Writer de lucene.
! */
! protected IndexWriter writer;
! /**
! * @see fr.emn.castor.recherche.metier.IIndexeur#addToIndex(
! * java.lang.String)
! */
! public final String addToIndex(final String idDocument)
! throws IndexationException {
! try {
! this.initWriter(false);
! this.indexSubDir = false;
! this.nbDocIndexes = 0;
! // on indexe le contenu du document ...
! this.indexDoc(idDocument);
! } catch (IOException ioe) {
! log.fatal("Erreur lors de l'initialisation du Writer !", ioe);
! throw new IndexationException(ioe.getMessage(), WRITER_ERROR);
! } finally {
! this.closeWriter();
! }
! return String.valueOf(this.nbDocIndexes);
! }
! /**
! * Methode indexant la notice correspondant a l'id donne en paramatre.
! *
! * @param idDocument
! * l'identifiant de la notice du document
! */
! protected final void indexNotice(final String idDocument)
! throws IndexationException {
! // on recupere la notice associée !
! File notice = new File(Facade.getInstance().getPathNotice(idDocument));
! this.docType = NOTICE;
! this.indexFichier(notice, idDocument);
! if (log.isDebugEnabled()) {
! log.debug("Fin d'indexation du document : "
! + Facade.getInstance().getNameDoc(idDocument));
! }
! }
! /**
! * @see fr.emn.castor.recherche.metier.IIndexeur#deleteRefFromIndex(
! * java.lang.String)
! */
! public final void deleteRefFromIndex(final String docId)
! throws IndexationException {
! if (log.isDebugEnabled()) {
! log.debug("Suppression de l'index pour le document " + docId);
! }
! try {
! String indexPath = Constants.CASTOR_INDEX_PATH;
! IndexReader reader = IndexReader.open(indexPath);
! Term term = new Term(RechercheConstants.KEYWORD_ID, docId);
! int deleted = reader.deleteDocuments(term);
! reader.close();
! if (log.isDebugEnabled()) {
! log
! .debug("Suppression OK , " + deleted
! + " item(s) supprimés.");
! }
! } catch (IOException ioe) {
! if (log.isDebugEnabled()) {
! log.fatal("Erreur lors de la suppression du doc " + docId
! + " de l'index.");
! }
! throw new IndexationException(ioe.getMessage(), IO_EXCEPTION);
! }
! }
! /**
! * Methode d'initialisation du writer.
! *
! * @param createNewIndex
! * indique si on ajoute des documents a l'index existant ou si on
! * en cree un nouveau, ecrasant l'ancien. <br>
! * <b>Attention, si l'index n'existe pas, la création sera
! * activée par défaut. </b> si true, creation d'un nouvel index,
! * et destruction de l'ancien. si false, ajout de documents dans
! * le nouvel index.
! * @throws IOException
! * si une erreur survient
! */
! protected void initWriter(final boolean createNewIndex) throws IOException {
! String indexDir = Constants.CASTOR_INDEX_PATH;
! boolean create = createNewIndex;
! // on va verifier avant si il existe ou pas un index.
! if (!IndexReader.indexExists(indexDir)) {
! // si l'index n'existe pas, on force la creation
! create = true;
! }
! this.writer = new IndexWriter(indexDir, new WhitespaceAnalyzer(),
! create);
! }
! /**
! * Methode permettant de fermer le writer.
! */
! protected void closeWriter() {
! try {
! this.writer.close();
! } catch (IOException ioe) {
! log.fatal("Erreur lors de la fermeture du writer : "
! + ioe.getMessage(), ioe);
! }
! }
! /**
! * Methode d'indexation du contenu du fichier donne.
! *
! * @param fichier
! * le fichier a indexer
! * @param id
! * identifiant du document correspondant au fichier
! * @throws IndexationException
! * Si il y a des erreurs lors de l'indexation.
! */
! protected void indexFichier(final File fichier, final String id)
! throws IndexationException {
! if (log.isDebugEnabled()) {
! log.debug("Indexation du document " + fichier + "...");
! }
! // Document Lucene
! Document doc = new Document();
! if (this.docType == -1) {
! throw new IndexationException(UNKNOWN_TYPE);
! }
! XMLLuceneIndexer xmlIndexer = new XMLLuceneIndexer(this.docType);
! doc = xmlIndexer.getDoc(fichier);
! // les fields specifiques au document
! try {
! // ajout du type de fichier (document/notice)
! Field typeField = new Field(
! RechercheConstants.KEYWORD_TYPE_FICHIER, String
! .valueOf(this.docType), Field.Store.YES,
! Field.Index.UN_TOKENIZED);
! doc.add(typeField);
! // ajout de l'id du document
! Field idField = new Field(RechercheConstants.KEYWORD_ID, id,
! Field.Store.YES, Field.Index.UN_TOKENIZED);
! doc.add(idField);
! this.writer.addDocument(doc);
! } catch (IOException ioe) {
! log.fatal(ioe.getMessage(), ioe);
! throw new IndexationException(IO_EXCEPTION);
! }
! // on incremente le nombre de documents indexes.
! this.nbDocIndexes += 1;
! }
! /**
! * Methode renvoyant une liste de resultats formates.
! *
! * @param hits
! * les hits lucene
! * @return une liste de Map.
! * @throws IOException
! * si une erreur survient lors de la lecture du hit.
! */
! private List<HashMap<String, String>> transformerHits(final Hits hits)
! throws IOException {
! List<HashMap<String, String>> resultHits = new ArrayList<HashMap<String, String>>();
! ArrayList<String> ids = new ArrayList<String>();
! for (int i = 0; i < hits.length(); i++) {
! Document doc = hits.doc(i);
! float score = hits.score(i);
! String ident = doc.get(RechercheConstants.KEYWORD_ID);
! HashMap<String, String> element = new HashMap<String, String>();
! String typeFichier = doc
! .get(RechercheConstants.KEYWORD_TYPE_FICHIER);
! if ((Integer.parseInt(typeFichier) == NOTICE)
! && (!ids.contains(ident))) {
! // on a recuperer la notice du doc..
! // on ajoute le score associe
! element.put(RechercheConstants.SEARCH_SCORE, String
! .valueOf(score));
! element.put(RechercheConstants.KEYWORD_ID, ident);
! element.putAll(Facade.getInstance().getNoticeMap(ident));
! } else {
! // on a recupere le document, mais a t'on deja la notice ??
! // si oui, inutile de recuperer la notice...
! if (!ids.contains(ident)) {
! // on va rechercher la notice
! element.put(RechercheConstants.SEARCH_SCORE, String
! .valueOf(score));
! element.put(RechercheConstants.KEYWORD_ID, ident);
! element.putAll(Facade.getInstance().getNoticeMap(ident));
! }
! }
! // ajout de l'element
! if (!element.isEmpty()) {
! resultHits.add(element);
! }
! ids.add(ident);
! }
! return resultHits;
! }
!
! /**
! * Methode renvoyant la liste des cahmps indexés.
! *
! * @return une liste de String.
! * @throws IOException
! * si une erreur survient lors de la lecture du hit.
! */
!
! public final List<String> getFieldNames() {
String indexDir = Constants.CASTOR_INDEX_PATH;
IndexSearcher searcher;
***************
*** 291,299 ****
try {
searcher = new IndexSearcher(indexDir);
! res = searcher.getIndexReader().getFieldNames();
! Iterator iter=res.iterator();
while (iter.hasNext()) {
String element = (String) iter.next();
! resultat.add(element);
}
} catch (Exception ioe) {
--- 300,308 ----
try {
searcher = new IndexSearcher(indexDir);
! res = searcher.getIndexReader().getFieldNames(FieldOption.INDEXED);
! Iterator iter = res.iterator();
while (iter.hasNext()) {
String element = (String) iter.next();
! resultat.add(element);
}
} catch (Exception ioe) {
***************
*** 305,374 ****
return resultat;
}
! /**
! * @see fr.emn.castor.recherche.metier.ISearcheur#search(java.util.Map)
! */
! public final List<HashMap<String, String>> search(final Map query) {
! List<HashMap<String, String>> results = new ArrayList<HashMap<String, String>>();
! String indexDir = Constants.CASTOR_INDEX_PATH;
! if (IndexReader.indexExists(indexDir)) {
! try {
! Searcher searcher = new IndexSearcher(indexDir);
! Analyzer analyzer = new WhitespaceAnalyzer();
! // construction de la requete lucene
! String queryText = "";
! Iterator keys = query.keySet().iterator();
! while (keys.hasNext()) {
! String key = (String) keys.next();
! // on ecarte la cle correspondant au type de requete
! if (!key.equals(UsersConstants.TYPE_RECHERCHE)) {
! String value = (String) query.get(key);
! if (value != null) {
! // on decoupe la valeur pour separer les chaines,
! // sinon lucene cherche la chaine complete au lieu
! // des mots
! String[] st = value.split("\\s");
! for (int i = 0; i < st.length; i++) {
! String token = st[i];
! if ((token != null) && (!token.equals(""))) {
! queryText += key + ":" + st[i] + " ";
! }
! }
! }
! }
! }
! if (queryText.equals("") || queryText.length() == 0) {
! // la chaine passée en parametre est vide !
! log.debug("requete vide, pas de resultat a renvoyer.");
! return results;
! }
! QueryParser parser = new QueryParser(
! RechercheConstants.KEYWORD_CONTENT, analyzer);
! Query luceneQuery = parser.parse(queryText);
! if (log.isDebugEnabled()) {
! log.debug("Recherche du terme : "
! + luceneQuery.toString());
! }
! Hits hits = searcher.search(luceneQuery);
! //Transformation du résultat (les hits) en itérateur de Map
! results = this.transformerHits(hits);
! searcher.close();
! } catch (IOException ioe) {
! if (log.isDebugEnabled()) {
! log.debug(ioe.getMessage(), ioe);
! }
! } catch (ParseException pe) {
! if (log.isDebugEnabled()) {
! log.debug(pe.getMessage(), pe);
! }
! }
! } else {
! // l'index n'a pas encore ete créé !
! if (log.isDebugEnabled()) {
! log.debug("Index inexistant, pas de resultats à renvoyer !");
! }
! }
! //retourne les resultats trouves
! return results;
! }
}
--- 314,383 ----
return resultat;
}
!
! /**
! * @see fr.emn.castor.recherche.metier.ISearcheur#search(java.util.Map)
! */
! public final List<HashMap<String, String>> search(final Map query) {
! List<HashMap<String, String>> results = new ArrayList<HashMap<String, String>>();
! String indexDir = Constants.CASTOR_INDEX_PATH;
! if (IndexReader.indexExists(indexDir)) {
! try {
! Searcher searcher = new IndexSearcher(indexDir);
! Analyzer analyzer = new WhitespaceAnalyzer();
! // construction de la requete lucene
! String queryText = "";
! Iterator keys = query.keySet().iterator();
! while (keys.hasNext()) {
! String key = (String) keys.next();
! // on ecarte la cle correspondant au type de requete
! if (!key.equals(UsersConstants.TYPE_RECHERCHE)) {
! String value = (String) query.get(key);
! if (value != null) {
! // on decoupe la valeur pour separer les chaines,
! // sinon lucene cherche la chaine complete au lieu
! // des mots
! String[] st = value.split("\\s");
! for (int i = 0; i < st.length; i++) {
! String token = st[i];
! if ((token != null) && (!token.equals(""))) {
! queryText += key + ":" + st[i] + " ";
! }
! }
! }
! }
! }
! if (queryText.equals("") || queryText.length() == 0) {
! // la chaine passée en parametre est vide !
! log.debug("requete vide, pas de resultat a renvoyer.");
! return results;
! }
! QueryParser parser = new QueryParser(
! RechercheConstants.KEYWORD_CONTENT, analyzer);
! Query luceneQuery = parser.parse(queryText);
! if (log.isDebugEnabled()) {
! log.debug("Recherche du terme : " + luceneQuery.toString());
! }
! Hits hits = searcher.search(luceneQuery);
! // Transformation du résultat (les hits) en itérateur de Map
! results = this.transformerHits(hits);
! searcher.close();
! } catch (IOException ioe) {
! if (log.isDebugEnabled()) {
! log.debug(ioe.getMessage(), ioe);
! }
! } catch (ParseException pe) {
! if (log.isDebugEnabled()) {
! log.debug(pe.getMessage(), pe);
! }
! }
! } else {
! // l'index n'a pas encore ete créé !
! if (log.isDebugEnabled()) {
! log.debug("Index inexistant, pas de resultats à renvoyer !");
! }
! }
! // retourne les resultats trouves
! return results;
! }
}
Plus d'informations sur la liste de diffusion Castore-commits