[Castore-commits] IndexationRechercheLucene.java 1.14 1.15

Neman OULD SID'AHMED neman at adullact1.hosting.cri74.org
Ven 11 Aou 16:09:43 CEST 2006


Update of /cvsroot/castore/castore-core/src/java/fr/emn/castor/recherche/metier/lucene
In directory adullact1:/tmp/cvs-serv2538/src/java/fr/emn/castor/recherche/metier/lucene

Modified Files:
	IndexationRechercheLucene.java 
Log Message:
Ajout d'une méthode qui récupère tous les champs indexés

Index: IndexationRechercheLucene.java
===================================================================
RCS file: /cvsroot/castore/castore-core/src/java/fr/emn/castor/recherche/metier/lucene/IndexationRechercheLucene.java,v
retrieving revision 1.14
retrieving revision 1.15
diff -C2 -d -r1.14 -r1.15
*** IndexationRechercheLucene.java	4 Aug 2006 14:51:08 -0000	1.14
--- IndexationRechercheLucene.java	11 Aug 2006 14:09:40 -0000	1.15
***************
*** 42,45 ****
--- 42,46 ----
  import java.io.IOException;
  import java.util.ArrayList;
+ import java.util.Collection;
  import java.util.HashMap;
  import java.util.Iterator;
***************
*** 51,54 ****
--- 52,57 ----
  import org.apache.lucene.analysis.Analyzer;
  import org.apache.lucene.analysis.SimpleAnalyzer;
+ import org.apache.lucene.analysis.WhitespaceAnalyzer;
+ import org.apache.lucene.analysis.standard.StandardAnalyzer;
  import org.apache.lucene.document.Document;
  import org.apache.lucene.document.Field;
***************
*** 62,65 ****
--- 65,69 ----
  import org.apache.lucene.search.Query;
  import org.apache.lucene.search.Searcher;
+ import org.apache.lucene.search.TermQuery;
  
  import fr.emn.castor.common.Constants;
***************
*** 74,346 ****
   * @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 SimpleAnalyzer(), 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;
!     }
  
!     /**
!      * @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 SimpleAnalyzer();
!                 // 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;
!     }
  
  }
--- 78,385 ----
   * @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));
! 		log
! 				.info("'IndexationRechercheLucene+indexNotice ', l'id du document indexé est  : "
! 						+ idDocument);
! 		this.docType = NOTICE;
! 		this.indexFichier(notice);
! 		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
! 	 * @throws IndexationException
! 	 *             Si il y a des erreurs lors de l'indexation.
! 	 */
! 	protected void indexFichier(final File fichier) 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 {
! 			String id = new File(fichier.getParent()).getName();
! 			// 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;
! 	}
  
! 	public final List getFieldNames() {
! 		String indexDir = Constants.CASTOR_INDEX_PATH;
! 		IndexSearcher searcher;
! 		List<String> resultat = new ArrayList();
! 		Collection res;
! 		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) {
! 			if (log.isDebugEnabled()) {
! 				log.debug(ioe.getMessage(), ioe);
! 			}
! 		}
! 
! 		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 {
! 				IndexSearcher 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