comparison src/goodjava/lucene/logging/LoggingIndexWriter.java @ 1461:e5d48b85351c

start lucene.logging
author Franklin Schmidt <fschmidt@gmail.com>
date Sat, 28 Mar 2020 21:30:42 -0600
parents
children 5e3870618377
comparison
equal deleted inserted replaced
1460:3ab0d043370f 1461:e5d48b85351c
1 package goodjava.lucene.logging;
2
3 import java.io.IOException;
4 import java.util.Map;
5 import org.apache.lucene.search.Query;
6 import goodjava.lucene.api.GoodIndexWriter;
7
8
9 public class LoggingIndexWriter implements GoodIndexWriter {
10 private static final int OP_DELETE_ALL = 1;
11 private static final int OP_DELETE_DOCUMENTS = 2;
12 private static final int OP_ADD_DOCUMENT = 3;
13 private static final int OP_UPDATE_DOCUMENT = 4;
14
15 public final GoodIndexWriter indexWriter;
16 private final LogFile logFile;
17
18 public LoggingIndexWriter(GoodIndexWriter indexWriter) throws IOException {
19 this.indexWriter = indexWriter;
20 logFile = new LogFile("lucene.log","rw");
21 logFile.gotoStart(); // for now
22 }
23
24 public void close() throws IOException {
25 indexWriter.close();
26 logFile.commit();
27 }
28
29 public void commit() throws IOException {
30 indexWriter.commit();
31 logFile.commit();
32 }
33
34 public void rollback() throws IOException {
35 indexWriter.rollback();
36 logFile.gotoEnd();
37 }
38
39 public void deleteAll() throws IOException {
40 indexWriter.deleteAll();
41 logFile.writeByte(OP_DELETE_ALL);
42 }
43
44 public void deleteDocuments(Query query) throws IOException {
45 indexWriter.deleteDocuments(query);
46 logFile.writeByte(OP_DELETE_DOCUMENTS);
47 logFile.writeQuery(query);
48 }
49
50 public void addDocument(Map<String,Object> storedFields) throws IOException {
51 indexWriter.addDocument(storedFields);
52 logFile.writeByte(OP_ADD_DOCUMENT);
53 logFile.writeMap(storedFields);
54 }
55
56 public void updateDocument(String keyFieldName,Map<String,Object> storedFields) throws IOException {
57 indexWriter.updateDocument(keyFieldName,storedFields);
58 logFile.writeByte(OP_UPDATE_DOCUMENT);
59 logFile.writeUTF(keyFieldName);
60 logFile.writeMap(storedFields);
61 }
62
63 public void reindexDocuments(String keyFieldName,Query query) throws IOException {
64 indexWriter.reindexDocuments(keyFieldName,query);
65 }
66
67 private void playOp() throws IOException {
68 int op = logFile.readByte();
69 switch(op) {
70 case OP_DELETE_ALL:
71 indexWriter.deleteAll();
72 return;
73 case OP_DELETE_DOCUMENTS:
74 indexWriter.deleteDocuments( logFile.readQuery() );
75 return;
76 case OP_ADD_DOCUMENT:
77 indexWriter.addDocument( logFile.readMap() );
78 return;
79 case OP_UPDATE_DOCUMENT:
80 indexWriter.updateDocument( logFile.readUTF(), logFile.readMap() );
81 return;
82 default:
83 throw new RuntimeException("invalid op "+op);
84 }
85 }
86
87 public void playLog() throws IOException {
88 logFile.gotoStart();
89 while( logFile.hasMore() ) {
90 playOp();
91 }
92 indexWriter.commit();
93 }
94 }