1 package org.apache.lucene.analysis.payloads;
3 * Licensed to the Apache Software Foundation (ASF) under one or more
4 * contributor license agreements. See the NOTICE file distributed with
5 * this work for additional information regarding copyright ownership.
6 * The ASF licenses this file to You under the Apache License, Version 2.0
7 * (the "License"); you may not use this file except in compliance with
8 * the License. You may obtain a copy of the License at
10 * http://www.apache.org/licenses/LICENSE-2.0
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
19 import java.io.IOException;
21 import org.apache.lucene.analysis.TokenFilter;
22 import org.apache.lucene.analysis.TokenStream;
23 import org.apache.lucene.analysis.tokenattributes.PayloadAttribute;
24 import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
28 * Characters before the delimiter are the "token", those after are the payload.
30 * For example, if the delimiter is '|', then for the string "foo|bar", foo is the token
31 * and "bar" is a payload.
33 * Note, you can also include a {@link org.apache.lucene.analysis.payloads.PayloadEncoder} to convert the payload in an appropriate way (from characters to bytes).
35 * Note make sure your Tokenizer doesn't split on the delimiter, or this won't work
39 public final class DelimitedPayloadTokenFilter extends TokenFilter {
40 public static final char DEFAULT_DELIMITER = '|';
41 private final char delimiter;
42 private final CharTermAttribute termAtt = addAttribute(CharTermAttribute.class);
43 private final PayloadAttribute payAtt = addAttribute(PayloadAttribute.class);
44 private final PayloadEncoder encoder;
47 public DelimitedPayloadTokenFilter(TokenStream input, char delimiter, PayloadEncoder encoder) {
49 this.delimiter = delimiter;
50 this.encoder = encoder;
54 public boolean incrementToken() throws IOException {
55 if (input.incrementToken()) {
56 final char[] buffer = termAtt.buffer();
57 final int length = termAtt.length();
58 for (int i = 0; i < length; i++) {
59 if (buffer[i] == delimiter) {
60 payAtt.setPayload(encoder.encode(buffer, i + 1, (length - (i + 1))));
61 termAtt.setLength(i); // simply set a new length
65 // we have not seen the delimiter
66 payAtt.setPayload(null);