1
22
23 package com.liferay.portal.search.lucene;
24
25 import com.liferay.portal.kernel.log.Log;
26 import com.liferay.portal.kernel.log.LogFactoryUtil;
27 import com.liferay.portal.kernel.search.Document;
28 import com.liferay.portal.kernel.search.Field;
29 import com.liferay.portal.kernel.search.IndexWriter;
30 import com.liferay.portal.kernel.search.SearchException;
31 import com.liferay.portal.kernel.util.Validator;
32
33 import java.io.IOException;
34
35 import java.util.Collection;
36
37 import org.apache.lucene.index.Term;
38
39
47 public class LuceneIndexWriterImpl implements IndexWriter {
48
49 public void addDocument(long companyId, Document doc)
50 throws SearchException {
51
52 org.apache.lucene.index.IndexWriter writer = null;
53
54 try {
55 writer = LuceneUtil.getWriter(companyId);
56
57 writer.addDocument(_getLuceneDocument(doc));
58
59 if (_log.isDebugEnabled()) {
60 _log.debug("Wrote document " + doc.get(Field.UID));
61 }
62 }
63 catch (IOException ioe) {
64 throw new SearchException(ioe);
65 }
66 finally {
67 if (writer != null) {
68 LuceneUtil.write(companyId);
69 }
70 }
71 }
72
73 public void deleteDocument(long companyId, String uid)
74 throws SearchException {
75
76 try {
77 LuceneUtil.deleteDocuments(companyId, new Term(Field.UID, uid));
78
79 if (_log.isDebugEnabled()) {
80 _log.debug("Deleted document " + uid);
81 }
82 }
83 catch (IOException ioe) {
84 throw new SearchException(ioe);
85 }
86 }
87
88 public void deletePortletDocuments(long companyId, String portletId)
89 throws SearchException {
90
91 try {
92 LuceneUtil.deleteDocuments(
93 companyId, new Term(Field.PORTLET_ID, portletId));
94 }
95 catch (IOException ioe) {
96 throw new SearchException(ioe);
97 }
98 }
99
100 public void updateDocument(long companyId, String uid, Document doc)
101 throws SearchException {
102
103 deleteDocument(companyId, uid);
104
105 addDocument(companyId, doc);
106 }
107
108 private org.apache.lucene.document.Document _getLuceneDocument(
109 Document doc) {
110
111 org.apache.lucene.document.Document luceneDoc =
112 new org.apache.lucene.document.Document();
113
114 Collection<Field> fields = doc.getFields().values();
115
116 for (Field field : fields) {
117 String name = field.getName();
118 boolean tokenized = field.isTokenized();
119 float boost = field.getBoost();
120
121 for (String value : field.getValues()) {
122 if (Validator.isNull(value)) {
123 continue;
124 }
125
126 org.apache.lucene.document.Field luceneField = null;
127
128 if (tokenized) {
129 luceneField = LuceneFields.getText(name, value);
130 }
131 else {
132 luceneField = LuceneFields.getKeyword(name, value);
133 }
134
135 luceneField.setBoost(boost);
136
137 luceneDoc.add(luceneField);
138 }
139 }
140
141 return luceneDoc;
142 }
143
144 private static Log _log =
145 LogFactoryUtil.getLog(LuceneIndexWriterImpl.class);
146
147 }