addTermPosition method

bool addTermPosition({
  1. required String term,
  2. required String docId,
  3. required Pt position,
  4. String? zone,
})

Adds or updates a posting position for the docId to PostingsMap entry for the term.

Returns true if the posting positions for the docId did not previously exist in the PostingsMap.

Looks up an existing entry for term and adds a position to the list of positions for docId if it exists.

If no entry for term exists in the PostingsMap, creates a new entry for term.

If zone is null, the posting position zone name is "null".

If no positions list exists for docId, creates a new position list for docId.

Adds position to the positions list for docId if it is not already in the list.

Sorts the positions list in ascending order.

Updates the term entry in the PostingsMap.

Implementation

bool addTermPosition(
    {required String term,
    required String docId,
    required Pt position,
    String? zone}) {
  //
  zone = zone ?? 'null';
  // get the entry for the term or initialize a new one if it does not exist
  final entry = this[term] ?? {};
  // get the existing zone postings for [docId] if it exists
  final docPostings = entry[docId] ?? {};
  // get the existing psitions in the zone for [zone] if it exists
  final docFieldPostings = docPostings[zone];
  // initializes positions set from docFieldPostings or an empty list
  final set = (docFieldPostings ?? []).toSet();
  // add position to the set
  set.add(position);
  // convert to list
  final positions = set.toList();
  // order the list of positions in ascending order
  positions.sort(((a, b) => a.compareTo(b)));
  // set the positions for docId
  docPostings[zone] = positions;
  // overwrite the zone postings for docId
  entry[docId] = docPostings;

  // set the entry for term with the new positions for docId
  this[term] = entry;
  // return true if a positions list for [docId] did not existed
  return docFieldPostings == null;
}