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