Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.
TypeScript boardcollaborationdocdocxexceloffce365officepdfpptpptxpresentationsdksheetslidesspreadsheetuniverwordwordprocessorworkspacexlsx
fix(formula): optimize the logic of inverted index (#6818)
wpxp12345679d2c30d68a4
diff --git a/packages/engine-formula/src/basics/inverted-index-cache.ts b/packages/engine-formula/src/basics/inverted-index-cache.tsindex 759f7b5c1e..34b3c5b3f3 100644--- a/packages/engine-formula/src/basics/inverted-index-cache.ts+++ b/packages/engine-formula/src/basics/inverted-index-cache.ts@@ -15,11 +15,43 @@*/import type { NumericTuple } from '@flatten-js/interval-tree';+import type { ErrorType } from './error-type';import IntervalTree from '@flatten-js/interval-tree';+import { isRealNum } from '@univerjs/core';+import { ERROR_TYPE_SET } from './error-type';++type ValueType = string | number | boolean;+type ValueTypeWithNullUndefined = ValueType | null | undefined;+type ValueTypeWithSymbol = ValueType | symbol;// empty cell, empty string and null value share the same inverted index cache keyexport const DEFAULT_EMPTY_CELL_KEY = Symbol('EMPTY_CELL');+const normalizedValueMap: Map<ValueTypeWithNullUndefined, ValueTypeWithSymbol> = new Map();++function normalizeValue(value: ValueTypeWithNullUndefined): ValueTypeWithSymbol {+ if (normalizedValueMap.has(value)) {+ return normalizedValueMap.get(value) as ValueTypeWithSymbol;+ }++ let _value: ValueTypeWithSymbol;++ if (value === null || value === undefined || value === '') {+ _value = DEFAULT_EMPTY_CELL_KEY;+ } else if (isRealNum(value) && Number(value).toString() === value.toString()) {+ // Number string that can be converted to number will be converted to number and stored in the inverted index cache, but '12a' or '012' will not be converted to number, because they are not pure number string.+ _value = Number(value) === 0 ? 0 : Number(value);+ } else if (typeof value === 'string') {+ // For string value, we will convert it to lower case to make the compare operation case-insensitive.+ _value = value.toLowerCase();+ } else {+ _value = value;+ }++ normalizedValueMap.set(value, _value);+ return _value;+}+export class InvertedIndexCache {/*** {@@ -33,11 +65,11 @@ export class InvertedIndexCache {* }* }*/- private _cache: Map<string, Map<string, Map<number, Map<string | number | boolean | null | symbol, Set<number>>>>> = new Map();+ private _cache: Map<string, Map<string, Map<number, Map<ValueTypeWithSymbol, Set<number>>>>> = new Map();private _continueBuildingCache: Map<string, Map<string, Map<number, IntervalTree<NumericTuple>>>> = new Map();- set(unitId: string, sheetId: string, column: number, value: string | number | boolean | null | symbol, row: number, isForceUpdate: boolean = false) {+ set(unitId: string, sheetId: string, column: number, value: ValueTypeWithNullUndefined, row: number, isForceUpdate: boolean = false) {if (!this.shouldContinueBuildingCache(unitId, sheetId, column, row) && !isForceUpdate) {return;}@@ -70,11 +102,7 @@ export class InvertedIndexCache {}}- // Because the inverted index cache is used for compare operation, it should be case-insensitive.- let _value = typeof value === 'string' ? value.toLowerCase() : value;- if (_value === '' || _value === null) {- _value = DEFAULT_EMPTY_CELL_KEY;- }+ const _value = normalizeValue(value);let cellList = columnMap.get(_value);if (cellList == null) {@@ -89,14 +117,44 @@ export class InvertedIndexCache {return this._cache.get(unitId)?.get(sheetId)?.get(column);}- getCellPositions(unitId: string, sheetId: string, column: number, value: string | number | boolean | null | symbol, rowsInCache: NumericTuple[]) {- // Because the inverted index cache is used for compare operation, it should be case-insensitive.- let _value = typeof value === 'string' ? value.toLowerCase() : value;- if (_value === '' || _value === null) {- _value = DEFAULT_EMPTY_CELL_KEY;+ getCellPositions(unitId: string, sheetId: string, column: number, value: ValueTypeWithNullUndefined, rowsInCache: NumericTuple[]): {+ errorType: ErrorType | null;+ matchingRows: number[];+ } | undefined {+ const columnMap = this._cache.get(unitId)?.get(sheetId)?.get(column);+ if (!columnMap) return;++ const result: {+ errorType: ErrorType | null;+ matchingRows: number[];+ } = {+ errorType: null,+ matchingRows: [],+ };++ const _value = normalizeValue(value);++ if (ERROR_TYPE_SET.has(_value as ErrorType)) {+ result.errorType = _value as ErrorType;+ } else if (_value === 0 || _value === DEFAULT_EMPTY_CELL_KEY) {+ const rows = [];++ const rowsForZero = columnMap.get(0);+ if (rowsForZero) {+ rows.push(...rowsForZero);+ }++ const rowsForEmpty = columnMap.get(DEFAULT_EMPTY_CELL_KEY);+ if (rowsForEmpty) {+ rows.push(...rowsForEmpty);+ }++ result.matchingRows = rows.filter((row) => rowsInCache.some(([start, end]) => row >= start && row <= end));+ } else {+ result.matchingRows = Array.from(columnMap.get(_value) ?? []).filter((row) => rowsInCache.some(([start, end]) => row >= start && row <= end));}- const rows = this._cache.get(unitId)?.get(sheetId)?.get(column)?.get(_value);- return rows && [...rows].filter((row) => rowsInCache.some(([start, end]) => row >= start && row <= end));++ return result;}setContinueBuildingCache(unitId: string, sheetId: string, column: number, startRow: number, endRow: number) {@@ -210,6 +268,7 @@ export class InvertedIndexCache {clear() {this._cache.clear();this._continueBuildingCache.clear();+ normalizedValueMap.clear();}private _handleNewInterval(columnMap: IntervalTree<NumericTuple>, startRow: number, endRow: number) {diff --git a/packages/engine-formula/src/engine/value-object/array-value-object.ts b/packages/engine-formula/src/engine/value-object/array-value-object.tsindex 381b945deb..cff8a0c020 100644--- a/packages/engine-formula/src/engine/value-object/array-value-object.ts+++ b/packages/engine-formula/src/engine/value-object/array-value-object.ts@@ -16,17 +16,24 @@import type { Nullable } from '@univerjs/core';import type { callbackMapFnType, IArrayValueObject } from './base-value-object';-import { isRealNum } from '@univerjs/core';import { BooleanValue } from '../../basics/common';import { ERROR_TYPE_SET, ErrorType } from '../../basics/error-type';-import { CELL_INVERTED_INDEX_CACHE, DEFAULT_EMPTY_CELL_KEY } from '../../basics/inverted-index-cache';+import { CELL_INVERTED_INDEX_CACHE } from '../../basics/inverted-index-cache';import { regexTestArrayValue } from '../../basics/regex';import { compareToken } from '../../basics/token';import { ArrayBinarySearchType, ArrayOrderSearchType, getCompare, isWildcard } from '../utils/compare';import { stringIsNumberPattern } from '../utils/numfmt-kit';import { BaseValueObject, ErrorValueObject } from './base-value-object';-import { BooleanValueObject, createBooleanValueObjectByRawValue, createNumberValueObjectByRawValue, createStringValueObjectByRawValue, NullValueObject, NumberValueObject, StringValueObject } from './primitive-object';+import {+ BooleanValueObject,+ createBooleanValueObjectByRawValue,+ createNumberValueObjectByRawValue,+ createStringValueObjectByRawValue,+ NullValueObject,+ NumberValueObject,+ StringValueObject,+} from './primitive-object';enum BatchOperatorType {MINUS,@@ -1530,7 +1537,6 @@ export class ArrayValueObject extends BaseValueObject {if (rowsInCache.length > 0) {if (operator === compareToken.EQUALS && !(valueObject.isString() && isWildcard(valueObject.getValue() as string))) {- // TODO@DR-Univer: When comparing equal with two parameters, one of them is error, and the logic here is wrongconst rowPositions = CELL_INVERTED_INDEX_CACHE.getCellPositions(unitId,sheetId,@@ -1539,8 +1545,8 @@ export class ArrayValueObject extends BaseValueObject {rowsInCache);- if (rowPositions != null) {- rowPositions.forEach((row) => {+ if (rowPositions !== undefined && rowPositions.errorType === null) {+ rowPositions.matchingRows.forEach((row) => {if (row < startRow || row > startRow + rowCount - 1) {return;}@@ -1730,23 +1736,13 @@ export class ArrayValueObject extends BaseValueObject {result[r][column] = ErrorValueObject.create(ErrorType.NA);}- if (!currentValue || currentValue?.isNull()) {- CELL_INVERTED_INDEX_CACHE.set(- unitId,- sheetId,- column + startColumn,- DEFAULT_EMPTY_CELL_KEY,- r + startRow- );- } else {- CELL_INVERTED_INDEX_CACHE.set(- unitId,- sheetId,- column + startColumn,- currentValue.getValue(),- r + startRow- );- }+ CELL_INVERTED_INDEX_CACHE.set(+ unitId,+ sheetId,+ column + startColumn,+ currentValue?.isNull() ? null : currentValue?.getValue(),+ r + startRow+ );}// eslint-disable-next-line max-lines-per-function, complexitydiff --git a/packages/sheets/src/controllers/__tests__/formula/array-inverted-index-cache7.spec.ts b/packages/sheets/src/controllers/__tests__/formula/array-inverted-index-cache7.spec.tsnew file mode 100644index 0000000000..491089ec87--- /dev/null+++ b/packages/sheets/src/controllers/__tests__/formula/array-inverted-index-cache7.spec.ts@@ -0,0 +1,162 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import type { CellValue, Ctor, Injector, IWorkbookData, Nullable, Worksheet } from '@univerjs/core';+import type { BaseFunction, IFunctionNames } from '@univerjs/engine-formula';+import type { FFormula } from '@univerjs/engine-formula/facade';+import { ICommandService, LocaleType } from '@univerjs/core';+import {+ FormulaDataModel,+ functionDate,+ functionInformation,+ functionLogical,+ functionMeta,+ IFormulaCurrentConfigService,+ IFormulaRuntimeService,+ IFunctionService,+ SetArrayFormulaDataMutation,+ SetFormulaCalculationNotificationMutation,+ SetFormulaCalculationResultMutation,+ SetFormulaCalculationStartMutation,+ SetFormulaCalculationStopMutation,+ SetTriggerFormulaCalculationStartMutation,+} from '@univerjs/engine-formula';+import { beforeEach, describe, expect, it } from 'vitest';+import { SetRangeValuesMutation } from '../../../commands/mutations/set-range-values.mutation';+import { createFunctionTestBed } from './create-function-test-bed';++import '@univerjs/engine-formula/facade';++const unitId = 'test';+const subUnitId = 'sheet1';++const getFunctionsTestWorkbookData = (): IWorkbookData => {+ return {+ id: unitId,+ appVersion: '3.0.0-alpha',+ styles: {},+ sheets: {+ sheet1: {+ id: subUnitId,+ cellData: {+ 39: {+ 5: {+ f: '=IF(ISBLANK(E40)," - ",IF(G40=0,E40,E40+G40-1))',+ },+ 8: {+ f: '=IF(OR(F40=0,E40=0)," - ",NETWORKDAYS(E40,F40))',+ },+ },+ },+ },+ },+ locale: LocaleType.EN_US,+ name: '',+ sheetOrder: [],+ };+};++describe('Test inverted index cache 6', () => {+ let get: Injector['get'];+ let worksheet: Worksheet;+ let formulaEngine: FFormula;+ let commandService: ICommandService;+ let formulaDataModel: FormulaDataModel;+ let getCellValue: (row: number, column: number) => Nullable<CellValue>;++ beforeEach(async () => {+ const testBed = createFunctionTestBed(getFunctionsTestWorkbookData());++ get = testBed.get;+ worksheet = testBed.sheet.getSheetBySheetId(subUnitId) as Worksheet;+ formulaEngine = testBed.api.getFormula() as FFormula;+ formulaDataModel = get(FormulaDataModel);++ commandService = get(ICommandService);++ commandService.registerCommand(SetFormulaCalculationStartMutation);+ commandService.registerCommand(SetTriggerFormulaCalculationStartMutation);+ commandService.registerCommand(SetFormulaCalculationStopMutation);+ commandService.registerCommand(SetFormulaCalculationResultMutation);+ commandService.registerCommand(SetFormulaCalculationNotificationMutation);+ commandService.registerCommand(SetArrayFormulaDataMutation);+ commandService.registerCommand(SetRangeValuesMutation);++ const functionService = get(IFunctionService);++ const formulaCurrentConfigService = get(IFormulaCurrentConfigService);++ const formulaRuntimeService = get(IFormulaRuntimeService);++ formulaCurrentConfigService.load({+ formulaData: {},+ arrayFormulaCellData: {},+ arrayFormulaRange: {},+ forceCalculate: false,+ dirtyRanges: [],+ dirtyNameMap: {},+ dirtyDefinedNameMap: {},+ dirtyUnitFeatureMap: {},+ dirtyUnitOtherFormulaMap: {},+ excludedCell: {},+ allUnitData: {+ [testBed.unitId]: testBed.sheetData,+ },+ });++ const sheetItem = testBed.sheetData[testBed.sheetId];++ formulaRuntimeService.setCurrent(+ 0,+ 0,+ sheetItem.rowCount,+ sheetItem.columnCount,+ testBed.sheetId,+ testBed.unitId+ );++ const functions = [+ ...functionMeta,+ ...functionLogical,+ ...functionInformation,+ ...functionDate,+ ]+ .map((registerObject) => {+ const Func = registerObject[0] as Ctor<BaseFunction>;+ const name = registerObject[1] as IFunctionNames;++ return new Func(name);+ });++ functionService.registerExecutors(+ ...functions+ );++ commandService.syncExecuteCommand(SetFormulaCalculationStartMutation.id, { forceCalculation: true }, { onlyLocal: true });+ await formulaEngine.onCalculationEnd();++ getCellValue = (row: number, column: number) => {+ return worksheet.getCellRaw(row, column)?.v;+ };+ });++ describe('Test formula', () => {+ it('Test blank cell compare number 0', () => {+ expect(getCellValue(39, 5)).toBe(' - ');+ expect(getCellValue(39, 8)).toBe(' - ');+ });+ });+});