MtasSolrComponentTermvector.java 56.3 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243
package mtas.solr.handler.component.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.Map.Entry;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.solr.common.params.ModifiableSolrParams;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.common.util.SimpleOrderedMap;
import org.apache.solr.handler.component.ResponseBuilder;
import org.apache.solr.handler.component.SearchComponent;
import org.apache.solr.handler.component.ShardRequest;
import org.apache.solr.handler.component.ShardResponse;

import mtas.codec.util.CodecUtil;
import mtas.codec.util.CodecComponent.ComponentField;
import mtas.codec.util.CodecComponent.ComponentFields;
import mtas.codec.util.CodecComponent.ComponentTermVector;
import mtas.codec.util.CodecComponent.SubComponentFunction;
import mtas.codec.util.collector.MtasDataCollector;
import mtas.codec.util.collector.MtasDataItemNumberComparator;
import mtas.parser.function.ParseException;
import mtas.solr.handler.component.MtasSolrSearchComponent;

/**
 * The Class MtasSolrComponentTermvector.
 */
public class MtasSolrComponentTermvector
    implements MtasSolrComponent<ComponentTermVector> {

  /** The Constant log. */
  private static final Log log = LogFactory
      .getLog(MtasSolrComponentTermvector.class);

  /** The search component. */
  MtasSolrSearchComponent searchComponent;

  /** The Constant PARAM_MTAS_TERMVECTOR. */
  public static final String PARAM_MTAS_TERMVECTOR = MtasSolrSearchComponent.PARAM_MTAS
      + ".termvector";

  /** The Constant NAME_MTAS_TERMVECTOR_FIELD. */
  public static final String NAME_MTAS_TERMVECTOR_FIELD = "field";

  /** The Constant NAME_MTAS_TERMVECTOR_KEY. */
  public static final String NAME_MTAS_TERMVECTOR_KEY = "key";

  /** The Constant NAME_MTAS_TERMVECTOR_PREFIX. */
  public static final String NAME_MTAS_TERMVECTOR_PREFIX = "prefix";

  /** The Constant NAME_MTAS_TERMVECTOR_REGEXP. */
  public static final String NAME_MTAS_TERMVECTOR_REGEXP = "regexp";

  /** The Constant NAME_MTAS_TERMVECTOR_FULL. */
  public static final String NAME_MTAS_TERMVECTOR_FULL = "full";

  /** The Constant NAME_MTAS_TERMVECTOR_TYPE. */
  public static final String NAME_MTAS_TERMVECTOR_TYPE = "type";

  /** The Constant NAME_MTAS_TERMVECTOR_SORT_TYPE. */
  public static final String NAME_MTAS_TERMVECTOR_SORT_TYPE = "sort.type";

  /** The Constant NAME_MTAS_TERMVECTOR_SORT_DIRECTION. */
  public static final String NAME_MTAS_TERMVECTOR_SORT_DIRECTION = "sort.direction";

  /** The Constant NAME_MTAS_TERMVECTOR_START. */
  public static final String NAME_MTAS_TERMVECTOR_START = "start";

  /** The Constant NAME_MTAS_TERMVECTOR_NUMBER. */
  public static final String NAME_MTAS_TERMVECTOR_NUMBER = "number";

  /** The Constant NAME_MTAS_TERMVECTOR_NUMBER_SHARDS. */
  public static final String NAME_MTAS_TERMVECTOR_NUMBER_SHARDS = "number.shards";

  /** The Constant NAME_MTAS_TERMVECTOR_FUNCTION. */
  public static final String NAME_MTAS_TERMVECTOR_FUNCTION = "function";

  /** The Constant NAME_MTAS_TERMVECTOR_FUNCTION_EXPRESSION. */
  public static final String NAME_MTAS_TERMVECTOR_FUNCTION_EXPRESSION = "expression";

  /** The Constant NAME_MTAS_TERMVECTOR_FUNCTION_KEY. */
  public static final String NAME_MTAS_TERMVECTOR_FUNCTION_KEY = "key";

  /** The Constant NAME_MTAS_TERMVECTOR_FUNCTION_TYPE. */
  public static final String NAME_MTAS_TERMVECTOR_FUNCTION_TYPE = "type";

  /** The Constant NAME_MTAS_TERMVECTOR_BOUNDARY. */
  public static final String NAME_MTAS_TERMVECTOR_BOUNDARY = "boundary";

  /** The Constant NAME_MTAS_TERMVECTOR_LIST. */
  public static final String NAME_MTAS_TERMVECTOR_LIST = "list";

  /** The Constant NAME_MTAS_TERMVECTOR_LIST_REGEXP. */
  public static final String NAME_MTAS_TERMVECTOR_LIST_REGEXP = "listRegexp";

  /** The Constant NAME_MTAS_TERMVECTOR_IGNORE_REGEXP. */
  public static final String NAME_MTAS_TERMVECTOR_IGNORE_REGEXP = "ignoreRegexp";

  /** The Constant NAME_MTAS_TERMVECTOR_IGNORE_LIST. */
  public static final String NAME_MTAS_TERMVECTOR_IGNORE_LIST = "ignoreList";

  /** The Constant NAME_MTAS_TERMVECTOR_IGNORE_LIST_REGEXP. */
  public static final String NAME_MTAS_TERMVECTOR_IGNORE_LIST_REGEXP = "ignoreListRegexp";

  /** The Constant SHARD_NUMBER_MULTIPLIER. */
  private static final int SHARD_NUMBER_MULTIPLIER = 2;

  /** The Constant DEFAULT_NUMBER. */
  private static final int DEFAULT_NUMBER = 10;

  /**
   * Instantiates a new mtas solr component termvector.
   *
   * @param searchComponent the search component
   */
  public MtasSolrComponentTermvector(MtasSolrSearchComponent searchComponent) {
    this.searchComponent = searchComponent;
  }

  /*
   * (non-Javadoc)
   * 
   * @see
   * mtas.solr.handler.component.util.MtasSolrComponent#prepare(org.apache.solr.
   * handler.component.ResponseBuilder,
   * mtas.codec.util.CodecComponent.ComponentFields)
   */
  public void prepare(ResponseBuilder rb, ComponentFields mtasFields)
      throws IOException {
    Set<String> ids = MtasSolrResultUtil
        .getIdsFromParameters(rb.req.getParams(), PARAM_MTAS_TERMVECTOR);
    if (!ids.isEmpty()) {
      int tmpCounter = 0;
      String[] fields = new String[ids.size()];
      String[] keys = new String[ids.size()];
      String[] prefixes = new String[ids.size()];
      String[] regexps = new String[ids.size()];
      String[] fulls = new String[ids.size()];
      String[] sortTypes = new String[ids.size()];
      String[] sortDirections = new String[ids.size()];
      String[] types = new String[ids.size()];
      String[] startValues = new String[ids.size()];
      String[] numbers = new String[ids.size()];
      String[] numberShards = new String[ids.size()];
      String[][] functionExpressions = new String[ids.size()][];
      String[][] functionKeys = new String[ids.size()][];
      String[][] functionTypes = new String[ids.size()][];
      String[] boundaries = new String[ids.size()];
      String[] lists = new String[ids.size()];
      Boolean[] listRegexps = new Boolean[ids.size()];
      String[] ignoreRegexps = new String[ids.size()];
      String[] ignoreLists = new String[ids.size()];
      Boolean[] ignoreListRegexps = new Boolean[ids.size()];
      for (String id : ids) {
        fields[tmpCounter] = rb.req.getParams().get(
            PARAM_MTAS_TERMVECTOR + "." + id + "." + NAME_MTAS_TERMVECTOR_FIELD,
            null);
        keys[tmpCounter] = rb.req.getParams().get(
            PARAM_MTAS_TERMVECTOR + "." + id + "." + NAME_MTAS_TERMVECTOR_KEY,
            String.valueOf(tmpCounter)).trim();
        prefixes[tmpCounter] = rb.req.getParams().get(PARAM_MTAS_TERMVECTOR
            + "." + id + "." + NAME_MTAS_TERMVECTOR_PREFIX, null);
        regexps[tmpCounter] = rb.req.getParams().get(PARAM_MTAS_TERMVECTOR + "."
            + id + "." + NAME_MTAS_TERMVECTOR_REGEXP, null);
        fulls[tmpCounter] = rb.req.getParams().get(
            PARAM_MTAS_TERMVECTOR + "." + id + "." + NAME_MTAS_TERMVECTOR_FULL,
            null);
        sortTypes[tmpCounter] = rb.req.getParams().get(PARAM_MTAS_TERMVECTOR
            + "." + id + "." + NAME_MTAS_TERMVECTOR_SORT_TYPE, null);
        sortDirections[tmpCounter] = rb.req.getParams()
            .get(PARAM_MTAS_TERMVECTOR + "." + id + "."
                + NAME_MTAS_TERMVECTOR_SORT_DIRECTION, null);
        startValues[tmpCounter] = rb.req.getParams().get(
            PARAM_MTAS_TERMVECTOR + "." + id + "." + NAME_MTAS_TERMVECTOR_START,
            null);
        numbers[tmpCounter] = rb.req.getParams().get(PARAM_MTAS_TERMVECTOR + "."
            + id + "." + NAME_MTAS_TERMVECTOR_NUMBER, null);
        numberShards[tmpCounter] = rb.req.getParams().get(PARAM_MTAS_TERMVECTOR
            + "." + id + "." + NAME_MTAS_TERMVECTOR_NUMBER_SHARDS, null);
        types[tmpCounter] = rb.req.getParams().get(
            PARAM_MTAS_TERMVECTOR + "." + id + "." + NAME_MTAS_TERMVECTOR_TYPE,
            null);
        Set<String> functionIds = MtasSolrResultUtil
            .getIdsFromParameters(rb.req.getParams(), PARAM_MTAS_TERMVECTOR
                + "." + id + "." + NAME_MTAS_TERMVECTOR_FUNCTION);
        functionExpressions[tmpCounter] = new String[functionIds.size()];
        functionKeys[tmpCounter] = new String[functionIds.size()];
        functionTypes[tmpCounter] = new String[functionIds.size()];
        int tmpSubCounter = 0;
        for (String functionId : functionIds) {
          functionKeys[tmpCounter][tmpSubCounter] = rb.req.getParams()
              .get(
                  PARAM_MTAS_TERMVECTOR + "." + id + "."
                      + NAME_MTAS_TERMVECTOR_FUNCTION + "." + functionId + "."
                      + NAME_MTAS_TERMVECTOR_FUNCTION_KEY,
                  String.valueOf(tmpSubCounter))
              .trim();
          functionExpressions[tmpCounter][tmpSubCounter] = rb.req.getParams()
              .get(PARAM_MTAS_TERMVECTOR + "." + id + "."
                  + NAME_MTAS_TERMVECTOR_FUNCTION + "." + functionId + "."
                  + NAME_MTAS_TERMVECTOR_FUNCTION_EXPRESSION, null);
          functionTypes[tmpCounter][tmpSubCounter] = rb.req.getParams()
              .get(PARAM_MTAS_TERMVECTOR + "." + id + "."
                  + NAME_MTAS_TERMVECTOR_FUNCTION + "." + functionId + "."
                  + NAME_MTAS_TERMVECTOR_FUNCTION_TYPE, null);
          tmpSubCounter++;
        }
        boundaries[tmpCounter] = rb.req.getParams().get(PARAM_MTAS_TERMVECTOR
            + "." + id + "." + NAME_MTAS_TERMVECTOR_BOUNDARY, null);
        lists[tmpCounter] = rb.req.getParams().get(
            PARAM_MTAS_TERMVECTOR + "." + id + "." + NAME_MTAS_TERMVECTOR_LIST);
        listRegexps[tmpCounter] = rb.req.getParams()
            .getBool(PARAM_MTAS_TERMVECTOR + "." + id + "."
                + NAME_MTAS_TERMVECTOR_LIST_REGEXP, false);
        ignoreRegexps[tmpCounter] = rb.req.getParams().get(PARAM_MTAS_TERMVECTOR
            + "." + id + "." + NAME_MTAS_TERMVECTOR_IGNORE_REGEXP, null);
        ignoreLists[tmpCounter] = rb.req.getParams().get(PARAM_MTAS_TERMVECTOR
            + "." + id + "." + NAME_MTAS_TERMVECTOR_IGNORE_LIST, null);
        ignoreListRegexps[tmpCounter] = rb.req.getParams()
            .getBool(PARAM_MTAS_TERMVECTOR + "." + id + "."
                + NAME_MTAS_TERMVECTOR_IGNORE_LIST_REGEXP, false);
        tmpCounter++;
      }
      String uniqueKeyField = rb.req.getSchema().getUniqueKeyField().getName();
      mtasFields.doTermVector = true;
      rb.setNeedDocSet(true);
      // init and checks
      for (String field : fields) {
        if (field == null || field.isEmpty()) {
          throw new IOException("no (valid) field in mtas termvector");
        } else if (!mtasFields.list.containsKey(field)) {
          mtasFields.list.put(field, new ComponentField(uniqueKeyField));
        }
      }
      MtasSolrResultUtil.compareAndCheck(keys, fields, NAME_MTAS_TERMVECTOR_KEY,
          NAME_MTAS_TERMVECTOR_FIELD, true);
      MtasSolrResultUtil.compareAndCheck(prefixes, fields,
          NAME_MTAS_TERMVECTOR_PREFIX, NAME_MTAS_TERMVECTOR_FIELD, false);
      MtasSolrResultUtil.compareAndCheck(regexps, fields,
          NAME_MTAS_TERMVECTOR_REGEXP, NAME_MTAS_TERMVECTOR_FIELD, false);
      MtasSolrResultUtil.compareAndCheck(types, fields,
          NAME_MTAS_TERMVECTOR_TYPE, NAME_MTAS_TERMVECTOR_FIELD, false);
      MtasSolrResultUtil.compareAndCheck(sortTypes, fields,
          NAME_MTAS_TERMVECTOR_SORT_TYPE, NAME_MTAS_TERMVECTOR_FIELD, false);
      MtasSolrResultUtil.compareAndCheck(sortDirections, fields,
          NAME_MTAS_TERMVECTOR_SORT_DIRECTION, NAME_MTAS_TERMVECTOR_FIELD,
          false);
      MtasSolrResultUtil.compareAndCheck(numbers, fields,
          NAME_MTAS_TERMVECTOR_NUMBER, NAME_MTAS_TERMVECTOR_FIELD, false);
      MtasSolrResultUtil.compareAndCheck(boundaries, fields,
          NAME_MTAS_TERMVECTOR_BOUNDARY, NAME_MTAS_TERMVECTOR_FIELD, false);
      MtasSolrResultUtil.compareAndCheck(lists, fields,
          NAME_MTAS_TERMVECTOR_LIST, NAME_MTAS_TERMVECTOR_FIELD, false);
      MtasSolrResultUtil.compareAndCheck(ignoreRegexps, fields,
          NAME_MTAS_TERMVECTOR_IGNORE_REGEXP, NAME_MTAS_TERMVECTOR_FIELD,
          false);
      MtasSolrResultUtil.compareAndCheck(ignoreLists, fields,
          NAME_MTAS_TERMVECTOR_IGNORE_LIST, NAME_MTAS_TERMVECTOR_FIELD, false);
      for (int i = 0; i < fields.length; i++) {
        if (!rb.req.getParams().getBool("isShard", false)) {
          numberShards[i] = null;
          boundaries[i] = null;
        }
        String field = fields[i];
        String prefix = (prefixes[i] == null) || (prefixes[i].isEmpty()) ? null
            : prefixes[i].trim();
        String key = (keys[i] == null) || (keys[i].isEmpty())
            ? String.valueOf(i) + ":" + field + ":" + prefix : keys[i].trim();
        String regexp = (regexps[i] == null) || (regexps[i].isEmpty()) ? null
            : regexps[i].trim();
        Boolean full = (fulls[i] == null) || (!fulls[i].equals("true")) ? false
            : true;
        String startValue = (startValues[i] == null)
            || (startValues[i].isEmpty()) ? null : startValues[i].trim();
        int listNumber = (numbers[i] == null) || (numbers[i].isEmpty())
            ? DEFAULT_NUMBER : Integer.parseInt(numbers[i]);
        int numberFinal = (numberShards[i] == null)
            || (numberShards[i].isEmpty()) ? listNumber
                : Integer.parseInt(numberShards[i]);
        String type = (types[i] == null) || (types[i].isEmpty()) ? null
            : types[i].trim();
        String sortType = (sortTypes[i] == null) || (sortTypes[i].isEmpty())
            ? null : sortTypes[i].trim();
        String sortDirection = (sortDirections[i] == null)
            || (sortDirections[i].isEmpty()) ? null : sortDirections[i].trim();
        String[] functionKey = functionKeys[i];
        String[] functionExpression = functionExpressions[i];
        String[] functionType = functionTypes[i];
        String boundary = boundaries[i];
        String[] list = null;
        Boolean listRegexp = listRegexps[i];
        if (lists[i] != null) {
          ArrayList<String> tmpList = new ArrayList<>();
          String[] subList = lists[i].split("(?<!\\\\),");
          for (int j = 0; j < subList.length; j++) {
            tmpList.add(subList[j].replace("\\,", ",").replace("\\\\", "\\"));
          }
          list = tmpList.toArray(new String[tmpList.size()]);
        }
        String ignoreRegexp = ignoreRegexps[i];
        String[] ignoreList = null;
        Boolean ignoreListRegexp = ignoreListRegexps[i];
        if (ignoreLists[i] != null) {
          ArrayList<String> tmpList = new ArrayList<>();
          String[] subList = ignoreLists[i].split("(?<!\\\\),");
          for (int j = 0; j < subList.length; j++) {
            tmpList.add(subList[j].replace("\\,", ",").replace("\\\\", "\\"));
          }
          ignoreList = tmpList.toArray(new String[tmpList.size()]);
        }

        if (prefix == null || prefix.isEmpty()) {
          throw new IOException("no (valid) prefix in mtas termvector");
        } else {
          try {
            mtasFields.list.get(field).termVectorList
                .add(new ComponentTermVector(key, prefix, regexp, full, type,
                    sortType, sortDirection, startValue, numberFinal,
                    functionKey, functionExpression, functionType, boundary,
                    list, listRegexp, ignoreRegexp, ignoreList,
                    ignoreListRegexp));
          } catch (ParseException e) {
            throw new IOException(e);
          }
        }
      }

    }
  }

  /*
   * (non-Javadoc)
   * 
   * @see
   * mtas.solr.handler.component.util.MtasSolrComponent#modifyRequest(org.apache
   * .solr.handler.component.ResponseBuilder,
   * org.apache.solr.handler.component.SearchComponent,
   * org.apache.solr.handler.component.ShardRequest)
   */
  public void modifyRequest(ResponseBuilder rb, SearchComponent who,
      ShardRequest sreq) {
    if (sreq.params.getBool(MtasSolrSearchComponent.PARAM_MTAS, false)) {
      if (sreq.params.getBool(PARAM_MTAS_TERMVECTOR, false)) {
        // compute keys
        Set<String> keys = MtasSolrResultUtil
            .getIdsFromParameters(rb.req.getParams(), PARAM_MTAS_TERMVECTOR);
        if ((sreq.purpose & ShardRequest.PURPOSE_GET_TOP_IDS) != 0) {
          for (String key : keys) {
            String oldNumber = sreq.params.get(PARAM_MTAS_TERMVECTOR + "." + key
                + "." + NAME_MTAS_TERMVECTOR_NUMBER);
            int number;
            if (oldNumber != null) {
              int oldNumberValue = Integer.parseInt(oldNumber);
              number = (oldNumberValue >= 0)
                  ? oldNumberValue * SHARD_NUMBER_MULTIPLIER : oldNumberValue;
            } else {
              number = DEFAULT_NUMBER * SHARD_NUMBER_MULTIPLIER;
            }
            sreq.params.add(
                PARAM_MTAS_TERMVECTOR + "." + key + "."
                    + NAME_MTAS_TERMVECTOR_NUMBER_SHARDS,
                String.valueOf(number));
          }
        } else {
          sreq.params.remove(PARAM_MTAS_TERMVECTOR);
          for (String key : keys) {
            sreq.params.remove(PARAM_MTAS_TERMVECTOR + "." + key + "."
                + NAME_MTAS_TERMVECTOR_FIELD);
            sreq.params.remove(PARAM_MTAS_TERMVECTOR + "." + key + "."
                + NAME_MTAS_TERMVECTOR_KEY);
            sreq.params.remove(PARAM_MTAS_TERMVECTOR + "." + key + "."
                + NAME_MTAS_TERMVECTOR_PREFIX);
            sreq.params.remove(PARAM_MTAS_TERMVECTOR + "." + key + "."
                + NAME_MTAS_TERMVECTOR_REGEXP);
            sreq.params.remove(PARAM_MTAS_TERMVECTOR + "." + key + "."
                + NAME_MTAS_TERMVECTOR_FULL);
            sreq.params.remove(PARAM_MTAS_TERMVECTOR + "." + key + "."
                + NAME_MTAS_TERMVECTOR_SORT_TYPE);
            sreq.params.remove(PARAM_MTAS_TERMVECTOR + "." + key + "."
                + NAME_MTAS_TERMVECTOR_SORT_DIRECTION);
            sreq.params.remove(PARAM_MTAS_TERMVECTOR + "." + key + "."
                + NAME_MTAS_TERMVECTOR_NUMBER);
            sreq.params.remove(PARAM_MTAS_TERMVECTOR + "." + key + "."
                + NAME_MTAS_TERMVECTOR_NUMBER_SHARDS);
            Set<String> functionKeys = MtasSolrResultUtil
                .getIdsFromParameters(rb.req.getParams(), PARAM_MTAS_TERMVECTOR
                    + "." + key + "." + NAME_MTAS_TERMVECTOR_FUNCTION);
            for (String functionKey : functionKeys) {
              sreq.params.remove(PARAM_MTAS_TERMVECTOR + "." + key + "."
                  + NAME_MTAS_TERMVECTOR_FUNCTION + "." + functionKey + "."
                  + NAME_MTAS_TERMVECTOR_FUNCTION_EXPRESSION);
              sreq.params.remove(PARAM_MTAS_TERMVECTOR + "." + key + "."
                  + NAME_MTAS_TERMVECTOR_FUNCTION + "." + functionKey + "."
                  + NAME_MTAS_TERMVECTOR_FUNCTION_KEY);
              sreq.params.remove(PARAM_MTAS_TERMVECTOR + "." + key + "."
                  + NAME_MTAS_TERMVECTOR_FUNCTION + "." + functionKey + "."
                  + NAME_MTAS_TERMVECTOR_FUNCTION_TYPE);
            }
            sreq.params.remove(PARAM_MTAS_TERMVECTOR + "." + key + "."
                + NAME_MTAS_TERMVECTOR_BOUNDARY);
            sreq.params.remove(PARAM_MTAS_TERMVECTOR + "." + key + "."
                + NAME_MTAS_TERMVECTOR_LIST);
            sreq.params.remove(PARAM_MTAS_TERMVECTOR + "." + key + "."
                + NAME_MTAS_TERMVECTOR_LIST_REGEXP);
            sreq.params.remove(PARAM_MTAS_TERMVECTOR + "." + key + "."
                + NAME_MTAS_TERMVECTOR_IGNORE_REGEXP);
            sreq.params.remove(PARAM_MTAS_TERMVECTOR + "." + key + "."
                + NAME_MTAS_TERMVECTOR_IGNORE_LIST);
            sreq.params.remove(PARAM_MTAS_TERMVECTOR + "." + key + "."
                + NAME_MTAS_TERMVECTOR_IGNORE_REGEXP);
          }
        }
      }
    }
  }

  /*
   * (non-Javadoc)
   * 
   * @see
   * mtas.solr.handler.component.util.MtasSolrComponent#create(mtas.codec.util.
   * CodecComponent.BasicComponent, java.lang.Boolean)
   */
  @SuppressWarnings("unchecked")
  public SimpleOrderedMap<Object> create(ComponentTermVector termVector,
      Boolean encode) throws IOException {
    SimpleOrderedMap<Object> mtasTermVectorResponse = new SimpleOrderedMap<>();
    mtasTermVectorResponse.add("key", termVector.key);

    termVector.subComponentFunction.dataCollector.close();

    HashMap<MtasDataCollector<?, ?>, HashMap<String, MtasSolrMtasResult>> functionData = new HashMap<>();
    HashMap<String, MtasSolrMtasResult> functionDataItem = new HashMap<>();
    functionData.put(termVector.subComponentFunction.dataCollector,
        functionDataItem);
    if (termVector.functions != null) {
      for (SubComponentFunction function : termVector.functions) {
        function.dataCollector.reduceToKeys(
            termVector.subComponentFunction.dataCollector.getKeyList());
        function.dataCollector.close();
        functionDataItem.put(function.key,
            new MtasSolrMtasResult(function.dataCollector,
                new String[] { function.dataType },
                new String[] { function.statsType },
                new SortedSet[] { function.statsItems }, new String[] { null },
                new String[] { null }, new Integer[] { 0 },
                new Integer[] { Integer.MAX_VALUE }, null));
      }
    }
    MtasSolrMtasResult data = new MtasSolrMtasResult(
        termVector.subComponentFunction.dataCollector,
        new String[] { termVector.subComponentFunction.dataType },
        new String[] { termVector.subComponentFunction.statsType },
        new SortedSet[] { termVector.subComponentFunction.statsItems },
        new String[] { termVector.subComponentFunction.sortType },
        new String[] { termVector.subComponentFunction.sortDirection },
        new Integer[] { 0 }, new Integer[] { termVector.number }, functionData);
    if (encode) {
      mtasTermVectorResponse.add("_encoded_list",
          MtasSolrResultUtil.encode(data));
    } else {
      mtasTermVectorResponse.add("list", data);
      MtasSolrResultUtil.rewrite(mtasTermVectorResponse, searchComponent);
    }
    return mtasTermVectorResponse;
  }

  /*
   * (non-Javadoc)
   * 
   * @see
   * mtas.solr.handler.component.util.MtasSolrComponent#finishStage(org.apache.
   * solr.handler.component.ResponseBuilder)
   */
  @SuppressWarnings("unchecked")
  public void finishStage(ResponseBuilder rb) {
    if (rb.req.getParams().getBool(MtasSolrSearchComponent.PARAM_MTAS, false)) {
      if (rb.stage >= ResponseBuilder.STAGE_EXECUTE_QUERY
          && rb.stage < ResponseBuilder.STAGE_GET_FIELDS) {
        for (ShardRequest sreq : rb.finished) {
          if (sreq.params.getBool(MtasSolrSearchComponent.PARAM_MTAS, false)
              && sreq.params.getBool(PARAM_MTAS_TERMVECTOR, false)) {
            for (ShardResponse shardResponse : sreq.responses) {
              NamedList<Object> response = shardResponse.getSolrResponse()
                  .getResponse();
              try {
                ArrayList<NamedList<Object>> data = (ArrayList<NamedList<Object>>) response
                    .findRecursive("mtas", "termvector");
                if (data != null) {
                  MtasSolrResultUtil.decode(data);
                }
              } catch (ClassCastException e) {
                log.debug(e);
                // shouldnt happen
              }
            }
          }
        }
        if (rb.stage == MtasSolrSearchComponent.STAGE_TERMVECTOR_FINISH) {
          if (rb.req.getParams().getBool(MtasSolrSearchComponent.PARAM_MTAS,
              false)
              && rb.req.getParams().getBool(PARAM_MTAS_TERMVECTOR, false)) {
            Set<String> ids = MtasSolrResultUtil.getIdsFromParameters(
                rb.req.getParams(), PARAM_MTAS_TERMVECTOR);
            if (!ids.isEmpty()) {
              int tmpCounter = 0;
              String[] keys = new String[ids.size()];
              String[] numbers = new String[ids.size()];
              for (String id : ids) {
                keys[tmpCounter] = rb.req.getParams()
                    .get(
                        PARAM_MTAS_TERMVECTOR + "." + id + "."
                            + NAME_MTAS_TERMVECTOR_KEY,
                        String.valueOf(tmpCounter))
                    .trim();
                numbers[tmpCounter] = rb.req.getParams()
                    .get(PARAM_MTAS_TERMVECTOR + "." + id + "."
                        + NAME_MTAS_TERMVECTOR_NUMBER, null);
                tmpCounter++;
              }
              // mtas response
              NamedList<Object> mtasResponse = null;
              try {
                mtasResponse = (NamedList<Object>) rb.rsp.getValues()
                    .get("mtas");
              } catch (ClassCastException e) {
                log.debug(e);
                mtasResponse = null;
              }
              if (mtasResponse == null) {
                mtasResponse = new SimpleOrderedMap<>();
                rb.rsp.add("mtas", mtasResponse);
              }
              Object o = mtasResponse.get("termvector");
              if (o != null && o instanceof ArrayList) {
                ArrayList<?> tvList = (ArrayList<?>) o;
                for (int i = 0; i < tmpCounter; i++) {
                  for (int j = 0; j < tvList.size(); j++) {
                    NamedList<Object> item = (NamedList<Object>) tvList.get(j);
                    boolean condition;
                    condition = item != null;
                    condition &= item.get("key") != null;
                    condition &= item.get("key") instanceof String;
                    condition &= item.get("list") != null;
                    condition &= item.get("list") instanceof ArrayList;
                    if (condition) {
                      String key = (String) item.get("key");
                      ArrayList<Object> list = (ArrayList<Object>) item
                          .get("list");
                      if (key.equals(keys[i])) {
                        int number;
                        if (numbers[i] != null) {
                          int numberValue = Integer.parseInt(numbers[i]);
                          number = numberValue >= 0 ? numberValue
                              : Integer.MAX_VALUE;
                        } else {
                          number = DEFAULT_NUMBER;
                        }
                        if (list.size() > number) {
                          item.removeAll("list");
                          item.add("list", list.subList(0, number));
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }

  /*
   * (non-Javadoc)
   * 
   * @see
   * mtas.solr.handler.component.util.MtasSolrComponent#distributedProcess(org.
   * apache.solr.handler.component.ResponseBuilder,
   * mtas.codec.util.CodecComponent.ComponentFields)
   */
  @Override
  public void distributedProcess(ResponseBuilder rb, ComponentFields mtasFields)
      throws IOException {
    if (rb.stage == MtasSolrSearchComponent.STAGE_TERMVECTOR_MISSING_TOP) {
      distributedProcessMissingTop(rb, mtasFields);
    } else if (rb.stage == MtasSolrSearchComponent.STAGE_TERMVECTOR_MISSING_KEY) {
      distributedProcessMissingKey(rb, mtasFields);
    } else if (rb.stage == MtasSolrSearchComponent.STAGE_TERMVECTOR_FINISH) {
      distributedProcessFinish(rb, mtasFields);
    }
  }

  /**
   * Distributed process finish.
   *
   * @param rb the rb
   * @param mtasFields the mtas fields
   * @throws IOException Signals that an I/O exception has occurred.
   */
  private void distributedProcessFinish(ResponseBuilder rb,
      ComponentFields mtasFields) throws IOException {
    // rewrite

    Object mtasResponseRaw;
    if ((mtasResponseRaw = rb.rsp.getValues().get("mtas")) != null
        && mtasResponseRaw instanceof NamedList) {
      NamedList<Object> mtasResponse = (NamedList<Object>) mtasResponseRaw;
      Object mtasResponseTermvectorRaw;
      if ((mtasResponseTermvectorRaw = mtasResponse.get("termvector")) != null
          && mtasResponseTermvectorRaw instanceof ArrayList) {
        MtasSolrResultUtil
            .rewrite((ArrayList<Object>) mtasResponseTermvectorRaw, searchComponent);
      }
    }
  }

  /**
   * Distributed process missing top.
   *
   * @param rb the rb
   * @param mtasFields the mtas fields
   * @throws IOException Signals that an I/O exception has occurred.
   */
  private void distributedProcessMissingTop(ResponseBuilder rb,
      ComponentFields mtasFields) throws IOException {
    // initialise
    Map<String, SortedMap<String, MtasDataItemNumberComparator>> mergedComparatorLists = new HashMap<>();
    Map<String, MtasDataItemNumberComparator> mergedComparatorBoundaryList = new HashMap<>();
    Map<String, MtasDataItemNumberComparator> summedComparatorBoundaryList = new HashMap<>();
    Map<String, Map<String, MtasDataItemNumberComparator>> comparatorBoundariesList = new HashMap<>();
    // check all termvectors, and initialize
    for (String field : mtasFields.list.keySet()) {
      List<ComponentTermVector> tvList = mtasFields.list
          .get(field).termVectorList;
      if (tvList != null) {
        for (ComponentTermVector tv : tvList) {
          if (!tv.subComponentFunction.sortType.equals(CodecUtil.SORT_TERM)) {
            mergedComparatorLists.put(tv.key,
                new TreeMap<String, MtasDataItemNumberComparator>());
          }
        }
      }
    }
    // compute for each termvector the mergedComparatorList and the
    // summedBoundary
    for (ShardRequest sreq : rb.finished) {
      if (sreq.params.getBool(MtasSolrSearchComponent.PARAM_MTAS, false)
          && sreq.params.getBool(PARAM_MTAS_TERMVECTOR, false)) {
        for (ShardResponse shardResponse : sreq.responses) {
          SortedMap<String, MtasDataItemNumberComparator> mergedComparatorList;
          NamedList<Object> response = shardResponse.getSolrResponse()
              .getResponse();
          String key;
          MtasSolrMtasResult list;
          MtasDataItemNumberComparator comparatorLast;
          Map<String, MtasDataItemNumberComparator> comparatorList;
          try {
            List<NamedList<Object>> data = (List<NamedList<Object>>) response
                .findRecursive("mtas", "termvector");
            if (data != null) {
              for (int i = 0; i < data.size(); i++) {
                NamedList<Object> dataItem = data.get(i);
                try {
                  key = (String) dataItem.get("key");
                  list = (MtasSolrMtasResult) dataItem.get("list");
                  if (list != null) {
                    comparatorLast = list.getResult().getLastSortValue();
                    comparatorList = list.getResult().getComparatorList();
                    if (key == null) {
                      dataItem.clear();
                    } else if (comparatorLast == null || comparatorList == null
                        || !mergedComparatorLists.containsKey(key)) {
                      // do nothing
                    } else {
                      mergedComparatorList = mergedComparatorLists.get(key);
                      for (Entry<String, MtasDataItemNumberComparator> entry : comparatorList
                          .entrySet()) {
                        if (mergedComparatorList.containsKey(entry.getKey())) {
                          mergedComparatorList.get(entry.getKey())
                              .add(entry.getValue().getValue());
                        } else {
                          mergedComparatorList.put(entry.getKey(),
                              entry.getValue().clone());
                        }
                      }
                      if (!comparatorBoundariesList.containsKey(key)) {
                        comparatorBoundariesList.put(key,
                            new HashMap<String, MtasDataItemNumberComparator>());
                      }
                      comparatorBoundariesList.get(key)
                          .put(shardResponse.getShardAddress(), comparatorLast);
                      if (summedComparatorBoundaryList.containsKey(key)) {
                        summedComparatorBoundaryList.get(key)
                            .add(comparatorLast.getValue());
                      } else {
                        summedComparatorBoundaryList.put(key,
                            comparatorLast.clone());
                      }
                    }
                  } else {
                    throw new IOException("no data returned");
                  }
                } catch (ClassCastException e) {
                  log.debug(e);
                  dataItem.clear();
                }
              }
            }
          } catch (ClassCastException e) {
            log.debug(e);
            // shouldnt happen
          }
          shardResponse.getSolrResponse().setResponse(response);
        }
      }
    }
    // compute for each relevant termvector the mergedComparatorBoundary
    HashMap<String, HashMap<String, HashMap<String, MtasDataItemNumberComparator>>> recomputeFieldList = new HashMap<>();
    for (String field : mtasFields.list.keySet()) {
      List<ComponentTermVector> tvList = mtasFields.list
          .get(field).termVectorList;
      if (tvList != null) {
        for (ComponentTermVector tv : tvList) {
          SortedMap<String, MtasDataItemNumberComparator> mergedComparatorList;
          if (mergedComparatorLists.containsKey(tv.key)) {
            mergedComparatorList = mergedComparatorLists.get(tv.key);
            if (mergedComparatorList.size() < tv.number || tv.number <= 0) {
              // do nothing
            } else {
              final int sortDirection = tv.subComponentFunction.sortDirection
                  .equals(CodecUtil.SORT_DESC) ? -1 : 1;
              SortedSet<Map.Entry<String, MtasDataItemNumberComparator>> sortedSet = new TreeSet<>(
                  (Map.Entry<String, MtasDataItemNumberComparator> e1,
                      Map.Entry<String, MtasDataItemNumberComparator> e2) -> (e1
                          .getValue().compareTo(e2.getValue().getValue()) == 0)
                              ? e1.getKey().compareTo(e2.getKey())
                              : e1.getValue().compareTo(
                                  e2.getValue().getValue()) * sortDirection);
              sortedSet.addAll(mergedComparatorLists.get(tv.key).entrySet());
              Optional<Map.Entry<String, MtasDataItemNumberComparator>> optionalItem = sortedSet
                  .stream().skip(tv.number - 1L).findFirst();
              if (optionalItem.isPresent()) {
                mergedComparatorBoundaryList.put(tv.key,
                    optionalItem.get().getValue());
              }
            }
          }
        }
      }
      HashMap<String, HashMap<String, MtasDataItemNumberComparator>> recomputeList = new HashMap<>();
      if (tvList != null) {
        for (ComponentTermVector tv : tvList) {
          String key = tv.key;
          if (mergedComparatorBoundaryList.containsKey(key)
              && summedComparatorBoundaryList.containsKey(key)) {
            // set termvector to recompute
            recomputeList.put(key,
                new HashMap<String, MtasDataItemNumberComparator>());
            // sort
            List<Entry<String, MtasDataItemNumberComparator>> list = new LinkedList<>(
                comparatorBoundariesList.get(key).entrySet());
            Collections.sort(list,
                (Entry<String, MtasDataItemNumberComparator> e1,
                    Entry<String, MtasDataItemNumberComparator> e2) -> e1
                        .getValue().compareTo(e2.getValue().getValue()));
            HashMap<String, MtasDataItemNumberComparator> sortedHashMap = new LinkedHashMap<>();
            for (Iterator<Map.Entry<String, MtasDataItemNumberComparator>> it = list
                .iterator(); it.hasNext();) {
              Map.Entry<String, MtasDataItemNumberComparator> entry = it.next();
              sortedHashMap.put(entry.getKey(), entry.getValue());
            }

            MtasDataItemNumberComparator mainNewBoundary = mergedComparatorBoundaryList
                .get(key).recomputeBoundary(sortedHashMap.size());
            // System.out.println(
            // "MAIN NEW BOUNDARY for '" + key + "' : " + mainNewBoundary);

            MtasDataItemNumberComparator sum = null;
            int number = 0;
            for (Entry<String, MtasDataItemNumberComparator> entry : sortedHashMap
                .entrySet()) {
              MtasDataItemNumberComparator newBoundary = mainNewBoundary
                  .clone();
              MtasDataItemNumberComparator currentBoundary = entry.getValue();
              int compare = currentBoundary.compareTo(newBoundary.getValue());
              if (tv.subComponentFunction.sortDirection
                  .equals(CodecUtil.SORT_DESC)) {
                compare *= -1;
              }
              if (compare < 0) {
                HashMap<String, MtasDataItemNumberComparator> recomputeSubList = new HashMap<>();
                // sum not null if number>0, but do check
                if (number > 0 && sum != null
                    && tv.subComponentFunction.sortDirection
                        .equals(CodecUtil.SORT_DESC)) {
                  MtasDataItemNumberComparator tmpSumBoundary = mergedComparatorBoundaryList
                      .get(key);
                  tmpSumBoundary.subtract(sum.getValue());
                  MtasDataItemNumberComparator alternativeNewBoundary = tmpSumBoundary
                      .recomputeBoundary(sortedHashMap.size() - number);
                  compare = newBoundary
                      .compareTo(alternativeNewBoundary.getValue());
                  if (compare < 0) {
                    newBoundary = alternativeNewBoundary;
                    compare = currentBoundary.compareTo(newBoundary.getValue());
                    if (tv.subComponentFunction.sortDirection
                        .equals(CodecUtil.SORT_DESC)) {
                      compare *= -1;
                    }
                    if (compare < 0) {
                      recomputeSubList.put(entry.getKey(), newBoundary);
                    }
                  } else {
                    recomputeSubList.put(entry.getKey(), newBoundary);
                  }
                } else {
                  recomputeSubList.put(entry.getKey(), newBoundary);
                }
                if (!recomputeSubList.isEmpty()) {
                  if (!recomputeList.containsKey(key)) {
                    recomputeList.put(key, recomputeSubList);
                  } else {
                    recomputeList.get(key).putAll(recomputeSubList);
                  }
                }
              } else {
                newBoundary = currentBoundary.clone();
              }
              if (sum == null) {
                sum = newBoundary.clone();
              } else {
                sum.add(newBoundary.getValue());
              }
              number++;
            }
          }
        }
      }
      if (!recomputeList.isEmpty()) {
        recomputeFieldList.put(field, recomputeList);
      }
    }

    // finally, recompute
    if (recomputeFieldList.size() > 0) {

      // remove output for termvectors in recompute list and get list of shards
      HashSet<String> shards = new HashSet<>();
      for (ShardRequest sreq : rb.finished) {
        if (sreq.params.getBool(MtasSolrSearchComponent.PARAM_MTAS, false)
            && sreq.params.getBool(PARAM_MTAS_TERMVECTOR, false)) {
          for (ShardResponse shardResponse : sreq.responses) {
            NamedList<Object> response = shardResponse.getSolrResponse()
                .getResponse();
            String key;
            String field;
            String shardAddress = shardResponse.getShardAddress();
            try {
              ArrayList<NamedList<Object>> data = (ArrayList<NamedList<Object>>) response
                  .findRecursive("mtas", "termvector");
              shards.add(shardAddress);
              if (data != null) {
                for (int i = 0; i < data.size(); i++) {
                  NamedList<Object> dataItem = data.get(i);
                  try {
                    key = (String) dataItem.get("key");
                    field = (String) dataItem.get("field");
                    boolean doClear;
                    doClear = field != null && key != null;
                    doClear = doClear ? recomputeFieldList.get(field) != null
                        : false;
                    doClear = doClear
                        ? recomputeFieldList.get(field).containsKey(key)
                        : false;
                    doClear = doClear ? recomputeFieldList.get(field).get(key)
                        .containsKey(shardAddress) : false;
                    if (doClear) {
                      dataItem.clear();
                      dataItem.add("key", key);
                    }
                  } catch (ClassCastException e) {
                    log.debug(e);
                    dataItem.clear();
                  }
                }
              }
            } catch (ClassCastException e) {
              log.debug(e);
              // shouldnt happen
            }
            shardResponse.getSolrResponse().setResponse(response);
          }
        }
      }

      // parameter
      HashMap<String, ModifiableSolrParams> requestParamList = new HashMap<>();
      for (String shardAddress : shards) {
        ModifiableSolrParams paramsNewRequest = new ModifiableSolrParams();
        int termvectorCounter = 0;
        for (String field : mtasFields.list.keySet()) {
          List<ComponentTermVector> tvList = mtasFields.list
              .get(field).termVectorList;
          if (recomputeFieldList.containsKey(field)) {
            HashMap<String, HashMap<String, MtasDataItemNumberComparator>> recomputeList = recomputeFieldList
                .get(field);
            if (tvList != null) {
              for (ComponentTermVector tv : tvList) {
                if (recomputeList.containsKey(tv.key)
                    && recomputeList.get(tv.key).containsKey(shardAddress)) {
                  paramsNewRequest.add(
                      PARAM_MTAS_TERMVECTOR + "." + termvectorCounter + "."
                          + NAME_MTAS_TERMVECTOR_BOUNDARY,
                      String.valueOf(recomputeList.get(tv.key).get(shardAddress)
                          .getValue()));
                  paramsNewRequest.add(PARAM_MTAS_TERMVECTOR + "."
                      + termvectorCounter + "." + NAME_MTAS_TERMVECTOR_FIELD,
                      field);
                  paramsNewRequest.add(PARAM_MTAS_TERMVECTOR + "."
                      + termvectorCounter + "." + NAME_MTAS_TERMVECTOR_PREFIX,
                      tv.prefix);
                  paramsNewRequest.add(PARAM_MTAS_TERMVECTOR + "."
                      + termvectorCounter + "." + NAME_MTAS_TERMVECTOR_KEY,
                      tv.key);
                  paramsNewRequest.add(
                      PARAM_MTAS_TERMVECTOR + "." + termvectorCounter + "."
                          + NAME_MTAS_TERMVECTOR_NUMBER,
                      String.valueOf(tv.number));
                  if (tv.subComponentFunction.sortType != null) {
                    paramsNewRequest.add(
                        PARAM_MTAS_TERMVECTOR + "." + termvectorCounter + "."
                            + NAME_MTAS_TERMVECTOR_SORT_TYPE,
                        tv.subComponentFunction.sortType);
                  }
                  if (tv.subComponentFunction.sortDirection != null) {
                    paramsNewRequest.add(
                        PARAM_MTAS_TERMVECTOR + "." + termvectorCounter + "."
                            + NAME_MTAS_TERMVECTOR_SORT_DIRECTION,
                        tv.subComponentFunction.sortDirection);
                  }
                  if (tv.subComponentFunction.type != null) {
                    paramsNewRequest.add(
                        PARAM_MTAS_TERMVECTOR + "." + termvectorCounter + "."
                            + NAME_MTAS_TERMVECTOR_TYPE,
                        tv.subComponentFunction.type);
                  }
                  if (tv.functions != null) {
                    int functionCounter = 0;
                    for (SubComponentFunction function : tv.functions) {
                      paramsNewRequest.add(
                          PARAM_MTAS_TERMVECTOR + "." + termvectorCounter + "."
                              + NAME_MTAS_TERMVECTOR_FUNCTION + "."
                              + functionCounter + "."
                              + NAME_MTAS_TERMVECTOR_FUNCTION_EXPRESSION,
                          function.expression);
                      paramsNewRequest.add(
                          PARAM_MTAS_TERMVECTOR + "." + termvectorCounter + "."
                              + NAME_MTAS_TERMVECTOR_FUNCTION + "."
                              + functionCounter + "."
                              + NAME_MTAS_TERMVECTOR_FUNCTION_KEY,
                          function.key);
                      if (function.type != null) {
                        paramsNewRequest.add(
                            PARAM_MTAS_TERMVECTOR + "." + termvectorCounter
                                + "." + NAME_MTAS_TERMVECTOR_FUNCTION + "."
                                + functionCounter + "."
                                + NAME_MTAS_TERMVECTOR_FUNCTION_TYPE,
                            function.type);
                      }
                      functionCounter++;
                    }
                  }
                  if (tv.regexp != null) {
                    paramsNewRequest.add(PARAM_MTAS_TERMVECTOR + "."
                        + termvectorCounter + "." + NAME_MTAS_TERMVECTOR_REGEXP,
                        tv.regexp);
                  }
                  termvectorCounter++;
                }
              }
            }
          }
        }
        if (!paramsNewRequest.getParameterNames().isEmpty()) {
          requestParamList.put(shardAddress, paramsNewRequest);
        }
      }

      // new requests
      for (Entry<String, ModifiableSolrParams> entry : requestParamList
          .entrySet()) {
        ShardRequest sreq = new ShardRequest();
        sreq.shards = new String[] { entry.getKey() };
        sreq.purpose = ShardRequest.PURPOSE_PRIVATE;
        sreq.params = entry.getValue();
        sreq.params.add("fq", rb.req.getParams().getParams("fq"));
        sreq.params.add("q", rb.req.getParams().getParams("q"));
        sreq.params.add("cache", rb.req.getParams().getParams("cache"));
        sreq.params.add("rows", "0");
        sreq.params.add(MtasSolrSearchComponent.PARAM_MTAS, rb.req
            .getOriginalParams().getParams(MtasSolrSearchComponent.PARAM_MTAS));
        sreq.params.add(PARAM_MTAS_TERMVECTOR,
            rb.req.getOriginalParams().getParams(PARAM_MTAS_TERMVECTOR));
        rb.addRequest(searchComponent, sreq);
      }
    }

  }

  /**
   * Distributed process missing key.
   *
   * @param rb the rb
   * @param mtasFields the mtas fields
   * @throws IOException Signals that an I/O exception has occurred.
   */
  private void distributedProcessMissingKey(ResponseBuilder rb,
      ComponentFields mtasFields) throws IOException {
    HashMap<String, HashMap<String, HashSet<String>>> missingTermvectorKeys = computeMissingTermvectorItemsPerShard(
        rb.finished, "mtas", "termvector");
    for (Entry<String, HashMap<String, HashSet<String>>> entry : missingTermvectorKeys
        .entrySet()) {
      HashMap<String, HashSet<String>> missingTermvectorKeysShard = entry
          .getValue();
      ModifiableSolrParams paramsNewRequest = new ModifiableSolrParams();
      int termvectorCounter = 0;
      for (String field : mtasFields.list.keySet()) {
        List<ComponentTermVector> tvList = mtasFields.list
            .get(field).termVectorList;
        if (tvList != null) {
          for (ComponentTermVector tv : tvList) {
            if (!tv.full) {
              if (missingTermvectorKeysShard.containsKey(tv.key)) {
                HashSet<String> list = missingTermvectorKeysShard.get(tv.key);
                if (!list.isEmpty()) {
                  paramsNewRequest.add(PARAM_MTAS_TERMVECTOR + "."
                      + termvectorCounter + "." + NAME_MTAS_TERMVECTOR_FIELD,
                      field);
                  paramsNewRequest.add(PARAM_MTAS_TERMVECTOR + "."
                      + termvectorCounter + "." + NAME_MTAS_TERMVECTOR_PREFIX,
                      tv.prefix);
                  paramsNewRequest.add(PARAM_MTAS_TERMVECTOR + "."
                      + termvectorCounter + "." + NAME_MTAS_TERMVECTOR_KEY,
                      tv.key);
                  if (tv.subComponentFunction.type != null) {
                    paramsNewRequest.add(
                        PARAM_MTAS_TERMVECTOR + "." + termvectorCounter + "."
                            + NAME_MTAS_TERMVECTOR_TYPE,
                        tv.subComponentFunction.type);
                  }
                  if (tv.functions != null) {
                    int functionCounter = 0;
                    for (SubComponentFunction function : tv.functions) {
                      paramsNewRequest.add(
                          PARAM_MTAS_TERMVECTOR + "." + termvectorCounter + "."
                              + NAME_MTAS_TERMVECTOR_FUNCTION + "."
                              + functionCounter + "."
                              + NAME_MTAS_TERMVECTOR_FUNCTION_EXPRESSION,
                          function.expression);
                      paramsNewRequest.add(
                          PARAM_MTAS_TERMVECTOR + "." + termvectorCounter + "."
                              + NAME_MTAS_TERMVECTOR_FUNCTION + "."
                              + functionCounter + "."
                              + NAME_MTAS_TERMVECTOR_FUNCTION_KEY,
                          function.key);
                      if (function.type != null) {
                        paramsNewRequest.add(
                            PARAM_MTAS_TERMVECTOR + "." + termvectorCounter
                                + "." + NAME_MTAS_TERMVECTOR_FUNCTION + "."
                                + functionCounter + "."
                                + NAME_MTAS_TERMVECTOR_FUNCTION_TYPE,
                            function.type);
                      }
                      functionCounter++;
                    }
                  }
                  if (tv.regexp != null) {
                    paramsNewRequest.add(PARAM_MTAS_TERMVECTOR + "."
                        + termvectorCounter + "." + NAME_MTAS_TERMVECTOR_REGEXP,
                        tv.regexp);
                  }
                  if (!list.isEmpty()) {
                    StringBuilder listValue = new StringBuilder();
                    String[] listList = list.toArray(new String[list.size()]);
                    for (int i = 0; i < listList.length; i++) {
                      if (i > 0) {
                        listValue.append(",");
                      }
                      listValue.append(listList[i].replace("\\", "\\\\")
                          .replace(",", "\\\\"));
                    }
                    paramsNewRequest.add(PARAM_MTAS_TERMVECTOR + "."
                        + termvectorCounter + "." + NAME_MTAS_TERMVECTOR_FULL,
                        "false");
                    paramsNewRequest
                        .add(
                            PARAM_MTAS_TERMVECTOR + "." + termvectorCounter
                                + "." + NAME_MTAS_TERMVECTOR_LIST,
                            listValue.toString());
                  }
                  termvectorCounter++;
                }
              }
            }
          }
          if (termvectorCounter > 0) {
            ShardRequest nsreq = new ShardRequest();
            nsreq.shards = new String[] { entry.getKey() };
            nsreq.purpose = ShardRequest.PURPOSE_PRIVATE;
            nsreq.params = new ModifiableSolrParams();
            nsreq.params.add("fq", rb.req.getParams().getParams("fq"));
            nsreq.params.add("q", rb.req.getParams().getParams("q"));
            nsreq.params.add("cache", rb.req.getParams().getParams("cache"));
            nsreq.params.add("rows", "0");
            nsreq.params.add(MtasSolrSearchComponent.PARAM_MTAS,
                rb.req.getOriginalParams()
                    .getParams(MtasSolrSearchComponent.PARAM_MTAS));
            nsreq.params.add(PARAM_MTAS_TERMVECTOR,
                rb.req.getOriginalParams().getParams(PARAM_MTAS_TERMVECTOR));
            nsreq.params.add(paramsNewRequest);
            rb.addRequest(searchComponent, nsreq);
          }
        }
      }
    }
  }

  /**
   * Compute missing termvector items per shard.
   *
   * @param requests the requests
   * @param args the args
   * @return the hash map
   * @throws IOException Signals that an I/O exception has occurred.
   */
  @SuppressWarnings("unchecked")
  private HashMap<String, HashMap<String, HashSet<String>>> computeMissingTermvectorItemsPerShard(
      List<ShardRequest> requests, String... args) throws IOException {
    HashMap<String, HashMap<String, HashSet<String>>> result = new HashMap<>();
    HashMap<String, HashMap<String, HashSet<String>>> itemsPerShardSets = new HashMap<>();
    HashMap<String, HashSet<String>> itemSets = new HashMap<>();
    // loop over responses different shards
    for (ShardRequest sreq : requests) {
      if (sreq.params.getBool(MtasSolrSearchComponent.PARAM_MTAS, false)
          && sreq.params.getBool(PARAM_MTAS_TERMVECTOR, false)) {
        for (ShardResponse shardResponse : sreq.responses) {
          NamedList<Object> response = shardResponse.getSolrResponse()
              .getResponse();
          try {
            // get termvector data
            ArrayList<NamedList<Object>> data = (ArrayList<NamedList<Object>>) response
                .findRecursive(args);
            if (data != null) {
              // loop over temvector results
              for (int i = 0; i < data.size(); i++) {
                NamedList<Object> dataItem = data.get(i);
                try {
                  // get termvector result
                  String termvectorKey = (String) dataItem.get("key");
                  MtasSolrMtasResult list = (MtasSolrMtasResult) dataItem
                      .get("list");
                  if (termvectorKey != null && list != null) {
                    // get keys
                    Set<String> keyList = list.getKeyList();
                    HashMap<String, HashSet<String>> itemsPerShardSet;
                    HashSet<String> itemSet;
                    HashSet<String> tmpItemSet = new HashSet<>();
                    if (itemsPerShardSets.containsKey(termvectorKey)) {
                      itemsPerShardSet = itemsPerShardSets.get(termvectorKey);
                      itemSet = itemSets.get(termvectorKey);
                    } else {
                      itemsPerShardSet = new HashMap<>();
                      itemSet = new HashSet<>();
                      itemsPerShardSets.put(termvectorKey, itemsPerShardSet);
                      itemSets.put(termvectorKey, itemSet);
                    }
                    itemsPerShardSet.put(shardResponse.getShardAddress(),
                        tmpItemSet);
                    tmpItemSet.addAll(keyList);
                    itemSet.addAll(keyList);
                  }
                } catch (ClassCastException e) {
                  log.debug(e);
                }
              }
            }
          } catch (ClassCastException e) {
            log.debug(e);
          }
        }
      }
    }

    // construct result
    for (Entry<String, HashSet<String>> entry : itemSets.entrySet()) {
      String termvectorKey = entry.getKey();
      HashSet<String> termvectorKeyList = entry.getValue();
      if (itemsPerShardSets.containsKey(termvectorKey)) {
        HashMap<String, HashSet<String>> itemsPerShardSet = itemsPerShardSets
            .get(termvectorKey);
        for (Entry<String, HashSet<String>> subEntry : itemsPerShardSet
            .entrySet()) {
          String shardName = subEntry.getKey();
          HashMap<String, HashSet<String>> tmpShardKeySet;
          if (result.containsKey(shardName)) {
            tmpShardKeySet = result.get(shardName);
          } else {
            tmpShardKeySet = new HashMap<>();
            result.put(shardName, tmpShardKeySet);
          }
          HashSet<String> tmpResult = new HashSet<>();
          HashSet<String> shardItemsSet = subEntry.getValue();
          for (String termvectorKeyListItem : termvectorKeyList) {
            if (!shardItemsSet.contains(termvectorKeyListItem)) {
              tmpResult.add(termvectorKeyListItem);
            }
          }
          tmpShardKeySet.put(termvectorKey, tmpResult);
        }
      }
    }
    return result;
  }

}