001    /*
002     * Copyright (C) 2008-2009 Holger Arndt, A. Naegele and M. Bundschus
003     *
004     * This file is part of the Java Data Mining Package (JDMP).
005     * See the NOTICE file distributed with this work for additional
006     * information regarding copyright ownership and licensing.
007     *
008     * JDMP is free software; you can redistribute it and/or modify
009     * it under the terms of the GNU Lesser General Public License as
010     * published by the Free Software Foundation; either version 2
011     * of the License, or (at your option) any later version.
012     *
013     * JDMP is distributed in the hope that it will be useful,
014     * but WITHOUT ANY WARRANTY; without even the implied warranty of
015     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
016     * GNU Lesser General Public License for more details.
017     *
018     * You should have received a copy of the GNU Lesser General Public
019     * License along with JDMP; if not, write to the
020     * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
021     * Boston, MA  02110-1301  USA
022     */
023    
024    package org.jdmp.lucene;
025    
026    import java.io.Closeable;
027    import java.io.File;
028    import java.io.Flushable;
029    import java.io.IOException;
030    import java.util.Collection;
031    import java.util.HashSet;
032    import java.util.List;
033    import java.util.Set;
034    
035    import org.apache.lucene.analysis.Analyzer;
036    import org.apache.lucene.analysis.standard.StandardAnalyzer;
037    import org.apache.lucene.document.Document;
038    import org.apache.lucene.document.Field;
039    import org.apache.lucene.document.Field.Store;
040    import org.apache.lucene.index.CorruptIndexException;
041    import org.apache.lucene.index.IndexReader;
042    import org.apache.lucene.index.IndexWriter;
043    import org.apache.lucene.index.Term;
044    import org.apache.lucene.index.IndexReader.FieldOption;
045    import org.apache.lucene.index.IndexWriter.MaxFieldLength;
046    import org.apache.lucene.queryParser.MultiFieldQueryParser;
047    import org.apache.lucene.search.BooleanClause;
048    import org.apache.lucene.search.BooleanQuery;
049    import org.apache.lucene.search.IndexSearcher;
050    import org.apache.lucene.search.Query;
051    import org.apache.lucene.search.ScoreDoc;
052    import org.apache.lucene.search.TopDocs;
053    import org.apache.lucene.search.BooleanClause.Occur;
054    import org.apache.lucene.store.Directory;
055    import org.apache.lucene.store.FSDirectory;
056    import org.jdmp.core.algorithm.indexer.AbstractIndexer;
057    import org.jdmp.core.dataset.DataSet;
058    import org.jdmp.core.dataset.DefaultDataSet;
059    import org.jdmp.core.sample.Sample;
060    import org.jdmp.core.variable.Variable;
061    import org.ujmp.core.Matrix;
062    import org.ujmp.core.interfaces.Erasable;
063    import org.ujmp.core.util.MathUtil;
064    import org.ujmp.core.util.SerializationUtil;
065    import org.ujmp.core.util.io.FileUtil;
066    
067    public class LuceneIndex extends AbstractIndexer implements Flushable,
068                    Closeable, Erasable {
069            private static final long serialVersionUID = -8483996550983833243L;
070    
071            private IndexWriter indexWriter = null;
072    
073            private IndexSearcher indexSearcher = null;
074    
075            private final Set<String> fields = new HashSet<String>();
076    
077            private Directory directory = null;
078    
079            private File path = null;
080    
081            private long runningId = 0;
082    
083            private final Analyzer analyzer = new StandardAnalyzer();
084    
085            private boolean readOnly = true;
086    
087            public LuceneIndex() throws Exception {
088                    this(null, false);
089            }
090    
091            public LuceneIndex(File path) throws Exception {
092                    this(path, false);
093            }
094    
095            public LuceneIndex(File path, boolean readOnly) throws Exception {
096                    this.readOnly = readOnly;
097                    if (path == null) {
098                            path = File.createTempFile("lucene", "");
099                            path.delete();
100                            path.mkdir();
101                            path.deleteOnExit();
102                            readOnly = false;
103                    }
104    
105                    fields.add(Sample.ID);
106    
107                    this.path = path;
108    
109                    directory = FSDirectory.getDirectory(path);
110    
111                    if (IndexReader.indexExists(directory)) {
112                            if (!readOnly) {
113                                    if (IndexWriter.isLocked(directory)) {
114                                            IndexWriter.unlock(directory);
115                                    }
116                                    indexWriter = new IndexWriter(directory, analyzer,
117                                                    MaxFieldLength.UNLIMITED);
118                            }
119    
120                            prepareReader();
121                            Collection<?> c = indexSearcher.getIndexReader().getFieldNames(
122                                            FieldOption.ALL);
123                            for (Object o : c) {
124                                    fields.add((String) o);
125                            }
126    
127                    } else if (!readOnly) {
128                            indexWriter = new IndexWriter(directory, analyzer, true,
129                                            MaxFieldLength.UNLIMITED);
130                    }
131            }
132    
133            @Override
134            public synchronized void add(Sample sample) throws Exception {
135                    if (readOnly || sample == null) {
136                            return;
137                    }
138    
139                    prepareWriter();
140                    Document doc = new Document();
141    
142                    String id = sample.getId();
143                    if (id == null) {
144                            id = "" + runningId++;
145                    }
146    
147                    doc.add(new Field(Sample.ID, id, Store.YES, Field.Index.NOT_ANALYZED));
148    
149                    for (Variable v : sample.getVariables()) {
150                            String key = v.getLabel();
151                            if (!Sample.ID.equals(key)) {
152                                    String value = "";
153                                    for (Matrix m : v.getMatrixList()) {
154                                            for (long[] c : m.availableCoordinates()) {
155                                                    value += " " + m.getAsString(c);
156                                            }
157                                    }
158                                    doc.add(new Field(key, value.trim(), Store.YES,
159                                                    Field.Index.ANALYZED));
160                                    fields.add(key);
161                            }
162                    }
163    
164                    doc.add(new Field("rawdata", SerializationUtil.serialize(sample),
165                                    Store.COMPRESS));
166    
167                    indexWriter.updateDocument(new Term(Sample.ID, id), doc);
168            }
169    
170            public int getSize() {
171                    try {
172                            if (indexWriter != null) {
173                                    return indexWriter.maxDoc();
174                            } else {
175                                    prepareReader();
176                                    return indexSearcher.maxDoc();
177                            }
178                    } catch (Exception e) {
179                            e.printStackTrace();
180                            return 0;
181                    }
182            }
183    
184            public synchronized Sample get(int index) throws Exception {
185                    prepareReader();
186                    if (indexSearcher.getIndexReader().isDeleted(index)) {
187                            return null;
188                    } else {
189                            Document doc = indexSearcher.doc(index);
190                            Sample s = (Sample) SerializationUtil.deserialize(doc
191                                            .getBinaryValue("rawdata"));
192                            return s;
193                    }
194            }
195    
196            public synchronized DataSet search(List<String> query) throws Exception {
197                    return search(query, 1000);
198            }
199    
200            public synchronized DataSet search(List<String> query, int count)
201                            throws Exception {
202                    BooleanQuery bq = new BooleanQuery();
203                    String[] fs = new String[fields.size()];
204                    MultiFieldQueryParser p = new MultiFieldQueryParser(fields.toArray(fs),
205                                    analyzer);
206    
207                    for (String s : query) {
208                            Query q = null;
209                            if ("*".equals(s)) {
210                                    q = p.parse("*");
211                            } else {
212                                    q = p.parse(s);
213                            }
214                            bq.add(new BooleanClause(q, Occur.SHOULD));
215                    }
216    
217                    return search(bq, count);
218            }
219    
220            public synchronized DataSet search(String query) throws Exception {
221                    return search(query, 1000);
222            }
223    
224            public synchronized DataSet search(String query, int count)
225                            throws Exception {
226                    String[] fs = new String[fields.size()];
227                    MultiFieldQueryParser p = new MultiFieldQueryParser(fields.toArray(fs),
228                                    analyzer);
229                    Query q = null;
230                    if (query == null || "".equals(query)) {
231                            q = p.parse("*");
232                    } else if ("*".equals(query)) {
233                            q = p.parse("*");
234                    } else {
235                            q = p.parse(query);
236                    }
237                    return search(q, count);
238            }
239    
240            public synchronized DataSet search(Query query, int count) throws Exception {
241                    prepareReader();
242                    TopDocs td = indexSearcher.search(query, count);
243                    DataSet result = new DefaultDataSet();
244                    for (ScoreDoc sd : td.scoreDocs) {
245                            int id = sd.doc;
246                            Document doc = indexSearcher.doc(id);
247                            Sample s = (Sample) SerializationUtil.deserialize(doc
248                                            .getBinaryValue("rawdata"));
249                            s.setMatrix(Sample.SCORE, MathUtil.getMatrix(sd.score));
250                            result.getSamples().add(s);
251                    }
252                    return result;
253            }
254    
255            private synchronized void prepareReader() throws CorruptIndexException,
256                            IOException {
257                    if (indexWriter != null) {
258                            indexWriter.commit();
259                    }
260                    if (indexSearcher != null
261                                    && !indexSearcher.getIndexReader().isCurrent()) {
262                            indexSearcher.close();
263                            indexSearcher = null;
264                    }
265                    if (indexSearcher == null) {
266                            indexSearcher = new IndexSearcher(directory);
267                    }
268            }
269    
270            private synchronized void prepareWriter() throws IOException {
271                    if (indexSearcher != null) {
272                            indexSearcher.close();
273                            indexSearcher = null;
274                    }
275            }
276    
277            @Override
278            public synchronized void flush() throws IOException {
279                    if (indexWriter != null) {
280                            indexWriter.commit();
281                    }
282            }
283    
284            public synchronized void optimize() throws IOException {
285                    if (indexWriter != null) {
286                            indexWriter.optimize();
287                    }
288            }
289    
290            @Override
291            public synchronized void close() throws IOException {
292                    if (indexSearcher != null) {
293                            indexSearcher.close();
294                            indexSearcher = null;
295                    }
296                    if (indexWriter != null) {
297                            indexWriter.close();
298                    }
299            }
300    
301            @Override
302            public synchronized void erase() throws IOException {
303                    if (readOnly) {
304                            return;
305                    }
306                    close();
307                    FileUtil.deleteRecursive(path);
308            }
309    
310    }