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